【问题标题】:How to read dictionaries in python? [closed]如何在python中阅读字典? [关闭]
【发布时间】:2016-06-17 11:17:48
【问题描述】:

我有一个名为“input.txt”的文件。在这个文本文件中存储了很多字典。我必须遍历这些字典。如何读取文件?每当我使用 open(), file.read() 读取文件时,它会将整个文本转换为字符串类型。如何将此文件作为字典集合读取?

input.txt 的内容:

{"label":18,"words":["realclearpolitics","-","election","2016","-","2016","republican","presidential","nomination","polls","year","state"]}

【问题讨论】:

  • 发布到目前为止您尝试过的内容?
  • 结尾}前少了一个]
  • 在关闭之前回滚您的问题,因为它提出了几个不相关的问题。

标签: python json file dictionary


【解决方案1】:

字符串中缺少结束列表括号。您可以使用this 之类的代码 - 与 python 的现有 json 模块:

import json

x = '{"label":18,"words":["realclearpolitics","-","election","2016","-","2016","republican","presidential","nomination","polls","year","state"]}'
j = json.loads(x)
print(j)

【讨论】:

    【解决方案2】:

    如果一行内容是格式良好的dict,可以在python中使用eval执行字符串

    line = {"label":18,"words":["realclearpolitics","-","election","2016","-","2016","republican","presidential","nomination","polls","year","state"]}
    dictionary = eval(line)
    print(dictionary)
    

    所以如果你只有那一行输入,你可以使用

    dictionary = eval(open("input.txt").read())
    

    或者如果你每行有一本字典

    with open('input.txt', 'r') as f:
        for line in f:
             dictionary = eval(line)
    

    【讨论】:

    • EVAL 是邪恶的 .. :D
    • 好吧,使用风险自负!只是指出这是可能的。如果您确定要评估的内容,它可能是一个有效的快速而肮脏的解决方案。
    • 我有很多行形式的字典。
    • 永远不要在 ast.literal_eval 可以使用的地方使用 eval。而且 json 并不完全是 Python 文字。
    • @IronFist:eval 是一个工具。像任何工具一样,它可以用于善或恶。
    【解决方案3】:

    使用json模块的方法将文件中每一行加载的str转换为dict

    import json
    
    with open('input.txt','r') as f:
        for line in f.readlines():
            line_as_dict = json.loads(line)
            # process here the dict
    

    【讨论】:

    • 假设我的字典是 {"words" : ['q', 'a', 'asa'], "values":[1,45,3]}。如何打印(字、值)?
    • @arihant34,首先您将其作为字典阅读,然后阅读如何使用字典(这与您在这里提出的问题完全不同。)
    • 此解决方案仅在每一行都是完整的 json 对象(或文件根本没有换行符)时才有效。为什么要这样拖你的代码?
    • 其实我是在处理大数据的,这里的文件是对文本执行tf-idf得到的。该文件采用多行格式,其中每一行是一个字典,表示一个文件。这本词典由单词和值组成。我想将每个单词映射到它的值。
    • 在这种情况下,@Gabor 的解决方案是完全正确的,实际上是必要的。 (一个 json 文件只能包含一个顶级对象。)但是要处理大数据,您应该使用更简洁/更紧凑的格式来转储数据。
    【解决方案4】:

    您可以尝试关注

    import ast
    import json
    
    def readfile():
        f = open(path_to_file, 'r')
        content = f.read()
        data = ast.literal_eval(content)
        print(json.loads(data))
    

    如果输入不是有效的 Python 数据类型,ast.literal_eval 会引发异常,因此如果不是,则不会执行代码。因此,从文件中读取的内容也会得到验证

    输出:

    {'label': 18,
     'words': ['realclearpolitics',
      '-',
      'election',
      '2016',
      '-',
      '2016',
      'republican',
      'presidential',
      'nomination',
      'polls',
      'year',
      'state']}
    

    【讨论】:

      【解决方案5】:

      您的 JSON 不正确,您错过了关闭数组,但更正后的 JSON 如下:

      {
          "label": 18,
          "words": ["realclearpolitics", "-", "election", "2016", "-", "2016", "republican", "presidential", "nomination", "polls", "year", "state"]
      }
      

      您可以使用json内置函数load读取JSON文件:

      import json
      with open(r'path\of\your\file') as data_file:
          jsonData = json.load(data_file)
          print jsonData # it will print whole JSON data
          print jsonData['words'] # it will print value of the key `word`
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-16
        • 1970-01-01
        • 2022-01-02
        • 1970-01-01
        • 2019-12-01
        • 2021-01-26
        • 2015-01-23
        相关资源
        最近更新 更多