在Python中,如何将一个文件读入包含多行条目的字典?

2024-09-29 05:27:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

n Name1 MiddleName1 Surname1
multiline
string1

n Name2 MiddleName2 Surname2
multi
line
string2


n Name3 MiddleName3 Surname3
multiline
string3

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

^{pr2}$

我试图用一个正则表达式来提取:

^{3}$

但我不知道该怎么办。我能找到的所有类似的问题都有某种分离(比如'='),可以用来将键从对象中分离出来。在


Tags: 文件数量line条目结构multimultilinename1
1条回答
网友
1楼 · 发布于 2024-09-29 05:27:32

如果文本文件中的格式与上面所述的一致,这应该不是一个大问题。 逐行读取文件,如果当前行不等于'\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)

我的输出:

^{pr2}$

相关问题 更多 >