python - 我怎样才能把这个文本文件转换成Python字典?

标签 python list dictionary

所以我有这个文本文件

(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",
}

关于python - 我怎样才能把这个文本文件转换成Python字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74452036/

相关文章:

python - 在 bash 中可视化树,如 unix "tree"的输出

python - socketIO-客户端 - 运行时错误 : maximum recursion depth exceeded

Python 与 MongoEngine - 访问自定义模型属性列表

list - flutter : Unsupported operation: Cannot add to an unmodifiable list

python - 将列表列表中的元素分组到嵌套字典中

arrays - Swift:访问字典数组中的数组值

python - 在 Tkinter 中自动换行文本的单行文本输入 UI 元素?

java - 在 Spring 4.1 中注入(inject)泛型列表

java - 使用具体类型的类创建列表

python从模块返回空字典