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 - 如何比较嵌套字典?

python - 使用twistd运行高速公路应用程序

python - 实现结果输出的最佳pythonic方式

r - 根据对象名称的字符向量创建列表

java - 如何通过拆分包含重复名称的 Map <String, List<Object>> 的键来创建新 Map

Python:Collections.Counter 与 defaultdict(int)

python - 使用附加条件合并两个数据框

python - 如何在 PyQt 中将键盘焦点带到 QTextEdit 上?

python - Numpy 将函数应用于数组中的每个项目

java - 使用 Java Streams 从 Nested List 和 Outer List 收集数据