【问题标题】:how to read multiple dictionaries from a file in python?如何从python中的文件中读取多个字典?
【发布时间】:2015-02-23 21:15:44
【问题描述】:

我对 python 比较陌生。 我正在尝试读取一个包含多个字典的 ascii 文件。该文件具有以下格式。

{Key1: value1
 key2: value2
 ...
}
{Key1: value1
 key2: value2
 ...
}
{
...

文件中的每个字典都是嵌套字典。 我正在尝试将其作为字典列表阅读。有什么简单的方法可以做到这一点吗? 我已经尝试了以下代码,但它似乎不起作用

data = json.load(open('doc.txt'))

【问题讨论】:

  • 你得到什么错误?

标签: python json python-2.7 file-io dictionary


【解决方案1】:
import re

fl = open('doc.txt', 'rb')

result = map(
    lambda part: dict(
        re.match(
            r'^\s*(.*?)\s*:\s*(.*?)\s*$', # splits with ':' ignoring space symbols
            line
        ).groups()
        for line in part.strip().split('\n') # splits with '\n', new line is a new key-value
    ),
    re.findall(
        r'\{(.*?)\}', # inside of { ... }
        fl.read(),
        flags=re.DOTALL # considering '\n'-symbols
    )
)

fl.close()

【讨论】:

    【解决方案2】:

    由于输入文件中的数据并不是真正的 JSON 或 Python 对象文字格式,因此您需要自己解析它。您还没有真正指定字典中允许的键和值是什么,所以下面只允许它们是字母数字字符串。

    所以给定一个包含以下内容的输入文件,命名为doc.txt

    {key1: value1
     key2: value2
     key3: value3
    }
    {key4: value4
     key5: value5
    }
    

    以下内容将其读取并转换为由字母数字键和值组成的 Python 字典列表:

    from pprint import pprint
    import re
    
    dictpat = r'\{((?:\s*\w+\s*:\s*\w+\s*)+)\}' # note non-capturing (?:) inner group
    itempat = r'(\s*(\w+)\s*:\s*(\w+)\s*)'      # which is captured in this expr
    
    with open('doc.txt') as f:
        lod = [{group[1]:group[2] for group in re.findall(itempat, items)}
                                    for items in re.findall(dictpat, f.read())]
    
    pprint(lod)
    

    输出:

    [{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
     {'key4': 'value4', 'key5': 'value5'}]
    

    【讨论】:

      【解决方案3】:

      如果内部元素是有效的 JSON,以下可以工作。我挖出了source of simplejson library 并对其进行了修改以适合您的用例。下面是一个 SSCCE。

      import re
      import simplejson
      
      FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
      WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS)
      
      def grabJSON(s):
          """Takes the largest bite of JSON from the string.
             Returns (object_parsed, remaining_string)
          """
          decoder = simplejson.JSONDecoder()
          obj, end = decoder.raw_decode(s)
          end = WHITESPACE.match(s, end).end()
          return obj, s[end:]
      
      def main():
          with open("out.txt") as f:
              s = f.read()
      
          while True:
              obj, remaining = grabJSON(s)
              print ">", obj
              s = remaining
              if not remaining.strip():
                  break
      

      .. 在 out.txt 中使用一些类似的 JSON 将输出如下内容:

      > {'hello': ['world', 'hell', {'test': 'haha'}]}
      > {'hello': ['world', 'hell', {'test': 'haha'}]}
      > {'hello': ['world', 'hell', {'test': 'haha'}]}
      

      【讨论】:

      • 完美运行 非常感谢,非常感谢。
      • 我在字典中有几个值是函数。例如' {key11: function(argument11) key12: {dict11}} {key21: function(argument12) key22: {dict21}} '是否可以扩展您的代码以读取这些字典。
      • 你能举一个更清楚的例子吗?可能是真实数据的简明版本。从您的key11function(argument11),很难弄清楚原始数据的结构——它是否包含引号?它包含逗号吗?是否需要调用函数等。您应该编辑您的问题并使用示例输入和输出进行更新。
      【解决方案4】:

      你必须把它放在一个大列表中才能让它工作。即

      [
          {key1: val1, key2: val2, key3: val3, ...keyN: valN}
          , {key1: val1, key2: val2, key3: val3, ...keyN: valN}
          , {key1: val1, key2: val2, key3: val3, ...keyN: valN}
          .
          .
          .
      ]
      

      如果你不能改变数据文件的格式,恐怕你就得滚动你自己的函数来解释数据了。

      【讨论】:

      • 那行不通。字典之间没有逗号。字典中的键值对之间没有逗号。
      猜你喜欢
      • 2014-08-31
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      • 2020-03-26
      • 2016-10-09
      • 1970-01-01
      • 1970-01-01
      • 2018-03-22
      相关资源
      最近更新 更多