【问题标题】:In Python, how do I read a file into a dictionary with multiple line entries? [closed]在 Python 中,如何将文件读入具有多行条目的字典中? [关闭]
【发布时间】:2018-09-14 11:15:26
【问题描述】:

我有一个具有以下结构的文件,并且条目之间有不同数量的换行符:

n Name1 MiddleName1 Surname1
multiline
string1

n Name2 MiddleName2 Surname2
multi
line
string2


n Name3 MiddleName3 Surname3
multiline
string3

如何将此文件读入包含以下内容的字典:

{"n Name1 MiddleName1 Surname1" : "multiline\nstring1", ...}

我尝试使用正则表达式提取键,如下所示:

with open('file') as infile:
    content = infile.read()
    match = re.search(r'n .*', content)

但我不知道从那里去哪里。我能找到的所有类似问题都有某种拆分(例如“=”),可用于将键与对象分开。

【问题讨论】:

标签: python file dictionary


【解决方案1】:

如果文本文件中的格式与上述一致,那应该不是什么大问题。 逐行读取文件,如果当前行不等于 '\n' (这将对应于空行),则将当前行视为您的密钥(尽管您可能希望去除尾随的 '\n')并将接下来的两行连接为您的字典的值。然后用这些更新你的字典并重复直到行==“”。 那应该这样做。请参阅下面的可能解决方案。不过可能还有其他更优雅的解决方案。

filename = ".//users.db"
users = {}
with open(filename,"r") as fin:
    line = fin.readline()

    # read until end of file
    while line != "":
        # check if you reached an empty line
        if line != "\n":
            content = ""
            next = fin.readline()
            # to allow for multiline you can use the while loop
            # just check if the next line is "\n" or "" to get out of the loop
            while next != "\n" and next != "":
                # for the value part of the dict just concat the next lines
                content += next
                next = fin.readline()
                # update the dict with 'line' as key and 'content' as value
            users.update({line.rstrip():content})
        # eat, sleep, repeat
        line = fin.readline() ### line adjusted for correct intendation

print(users)

我的输出:

{'n Name1 MiddleName1 Surname1': 'multiline\nstring1\n', 'n Name2 MiddleName2 Surname2': 'multiline\nstring2\n', 'n Name3 MiddleName3 Surname3': 'multiline\nstring3'}

【讨论】:

  • 感谢您的回答!我忘了提到每个对象中的行数也是不同的。对于那个很抱歉。我编辑了我的问题以反映这一点。有没有办法在不固定变量中的行数的情况下做到这一点?
  • 您可以使用 while 循环代替 for 循环,该循环检查您是否到达了一个空行,即 '\n' 并继续连接直到那时。
  • 嗨,我用上述更改更新了代码。
  • 成功了,非常感谢!
  • 嗨,只是一个调整。最后一个 'line = fin.readline() 不应该像上面的列表那样。我刚刚调整好了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-06
  • 2013-04-30
相关资源
最近更新 更多