我有了这个文本文件
(1, 15), 'indice3 = [4, 5, 6]'
(7, 1), "indice1 = {3: 'A B C'}"
(11, 7), "indice4 = '(1, 2)'"
(11, 17), 'typage = mode de déclaration des types de variable'
(23, 5), "indice5 = '(3, 4)'"
(25, 1), '27 * 37 = 999'
如你所见,首先是坐标,然后是文本。
下面是一个示例,它看起来像在末尾(对于前两个元素)
{
(1,15): "indice3 = [4, 5, 6]",
(7, 1): "indice1 = {3: 'A B C'}"
}
我知道我应该从读取文件(f = open("dico_objets.txt", "r")
)开始,然后逐行读取,但我不知道如何正确分割它。
尝试使用ast.literal_eval
:
from ast import literal_eval
out = []
with open("your_file.txt", "r") as f_in:
for line in map(str.strip, f_in):
if line == "":
continue
out.append(literal_eval(f"[{line}]"))
print(dict(out))
打印:
{
(1, 15): "indice3 = [4, 5, 6]",
(7, 1): "indice1 = {3: 'A B C'}",
(11, 7): "indice4 = '(1, 2)'",
(11, 17): "typage = mode de déclaration des types de variable",
(23, 5): "indice5 = '(3, 4)'",
(25, 1): "27 * 37 = 999",
}
您可以在每行使用find()
。逐行读取文件,并执行如下命令
split_point = line.find(',', line.find(',')+1)
out_dict[line[:split_point]] = line[split_point:]