如何在python中从一个文件中读取多个词典?

如何在python中从一个文件中读取多个词典?,python,json,python-2.7,file-io,dictionary,Python,Json,Python 2.7,File Io,Dictionary,我对python比较陌生。 我正在尝试读取包含多个词典的ascii文件。该文件具有以下格式 {Key1: value1 key2: value2 ... } {Key1: value1 key2: value2 ... } { ... 文件中的每个词典都是嵌套词典。 我试着把它当作一个字典列表来读。有什么简单的方法可以做到这一点吗? 我试过下面的代码,但似乎不起作用 data = json.load(open('doc.txt')) 你必须把它放在一个大的列表中才能让它工作。i、 e

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

{Key1: value1
 key2: value2
 ...
}
{Key1: value1
 key2: value2
 ...
}
{
...
文件中的每个词典都是嵌套词典。 我试着把它当作一个字典列表来读。有什么简单的方法可以做到这一点吗? 我试过下面的代码,但似乎不起作用

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

你必须把它放在一个大的列表中才能让它工作。i、 e

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

如果您无法更改数据文件格式,恐怕您将不得不使用自己的函数来解释数据。

如果内部元素是有效的JSON,以下操作可能会起作用。我挖掘了这个文档并修改它以适合您的用例。下面是一个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'}]}

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

因此,给定了一个名为
doc.txt的输入文件:

{key1:value1
键2:值2
键3:值3
}
{key4:value4
键5:值5
}
以下内容将其读取并转换为由字母数字键和值组成的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'}]

您会遇到什么错误?这不起作用。字典之间没有逗号。字典中的键值对之间没有逗号。非常感谢,我非常感谢。字典中有几个值是函数。例如,{key11:function(argument11)key12:{dict11}}{key21:function(argument12)key22:{dict21}}是否可以扩展您的代码来阅读这些字典。您能给出一个更清楚的例子吗?可能是真实数据的简明版本。从您的
key11
函数(argument11)
,很难看出原始数据的结构-它是否包含引号?它是否包含逗号?是否需要调用函数等。。您应该编辑您的问题,并使用示例输入和输出进行更新。
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()