【问题标题】:Taking a dictionary from a text file从文本文件中获取字典
【发布时间】:2016-02-15 17:12:05
【问题描述】:

我有一个字典存储在一个名为“Dict.txt”的文本文件中,如下所示:

[{1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 15: 0}]

我有一些代码可以把这个文件变成字典:

import json, ast

file = open('Dict.txt', 'r')
save = file.read()
file.close()
for func in (ast.literal_eval, json.loads):
    file = func(save)
file = file[0]

但是当我运行代码时,我得到了错误:

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)

我不习惯使用字典、json 或 ast。所以我知道为什么会发生这种情况,我们将不胜感激。

【问题讨论】:

    标签: python json python-3.x dictionary


    【解决方案1】:

    这不是有效的 JSON,因为最外层的结构是一个列表,而不是一个字典,并且键是数字而不是字符串。你仍然可以像这样使用literal_eval:

    file = open('Dict.txt', 'r')
    your_list_with_a_dict = ast.literal_eval(file.read())
    your_dict = your_list_with_a_dict[0]
    file.close()
    

    【讨论】:

    • 这行得通,但如果我有一个数组,它只会打开第一项。我该怎么做?
    • your_list_with_a_dict[0] 只取出第一项。你想对剩下的物品做什么?你也可以直接使用ast.literal_eval(file.read())的结果,都在里面。
    • 感谢您的帮助!我只是想知道,“信任输入”是什么意思?
    【解决方案2】:

    当您从文件中读取数据时,您可以只使用literal_eval。所以,你可以简单地这样做:

    test.txt的内容:

    [{1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 15: 0}]
    

    读取文件并以所需数据结构输出的代码:

    from ast import literal_eval
    data = []
    with open('test.txt') as a:
        data = literal_eval(a.read())
    print(data)
    

    输出:

    [{1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 15: 0}]
    

    【讨论】:

      【解决方案3】:

      正则表达式是你最好的朋友:)

      import re
      import ast
      file = open('dict.txt', 'r')
      save = file.read()
      file.close()
      result = re.search('\[(.*)\]',save)
      my_dict = result.group(1)
      print my_dict
      my_dict = ast.literal_eval(my_dict)
      print type(my_dict)
      print my_dict
      

      【讨论】:

        猜你喜欢
        • 2020-03-26
        • 1970-01-01
        • 1970-01-01
        • 2016-08-04
        • 2017-12-20
        • 1970-01-01
        • 1970-01-01
        • 2021-04-15
        • 1970-01-01
        相关资源
        最近更新 更多