简体   繁体   English

如何在特定于Python的文件类型中将文件读入字典

[英]How to read file into dictionary in Python specific filetype

Specifically, I have a text file with multiple lines arranged so that the key of each entry is the first line of a group, followed by its related values, followed by a newline before the next key. 具体来说,我有一个文本文件,该文件有多行排列,因此每个条目的键是组的第一行,其后是相关值,然后是下一个键之前的换行符。 I'm having a hard time using while loops to accomplish this with readline. 我很难使用while循环来通过readline完成此操作。

For example the first line may be a restaurant name, followed by several lines of customers who ate there, which I then need to write into the values of a dictionary under the key of a restaurant name. 例如,第一行可能是餐厅名称,然后是在那儿用餐的几行客户,然后我需要在餐厅名称键下将其写入字典的值。

I'm really unfamiliar with file reading so I'm afraid that what I have is not going to help at all really. 我真的不熟悉文件读取,因此我担心我所拥有的根本无法提供任何帮助。

Something like this I guess, but it's not even to the point of semi-functional. 我猜是这样的,但是还没有达到半功能性。

edit: Thanks for the response I should have clarified, each value item for a corresponding key is listed in subsequent lines after the key with the a blank line at the end of that list preceding the next key. 编辑:感谢您应该澄清的答复,相应键的每个值项在键后的后续行中列出,该行末尾的空白行在下一个键之前。 Also I am unfortunately compelled to use a readline approach here. 同样不幸的是,我不得不在这里使用readline方法。

    restaurants = {}
    patrons = []

    line = file.readline()
    s = line.strip('\n')

    while s != ''
    restaurant = s
    line = file.readline
    patrons.append(s)

Assuming your text file looks like this 假设您的文本文件如下所示

mcdonalds bill bo bob 麦当劳比尔·鲍勃

as per 按照

I have a text file with multiple lines arranged so that the key of each entry is the first line of a group, followed by its related values, followed by a newline 我有一个排列有多行的文本文件,因此每个条目的键是组的第一行,其后是相关值,然后是换行符

my_dict = {}

with open("rest.txt", 'r') as f:
    for line in f:
        items = line.split()
        key, values = items[0], items[1:]
        my_dict[key] = values


print my_dict

which will produce 会产生

{'mcdonalds': ['bill', 'bo', 'bob']}

EDIT: revised according to the new problem specification. 编辑:根据新的问题规范进行了修订。

with open("filename") as f:
    lines = f.readlines()
restaurants = {}
current_key = None
for line in lines:
    line = line.strip()
    if not line:
        current_key = None
    elif not current_key:
        current_key = line
        restaurants[current_key] = []
    else:
        restaurants[current_key].append(line)

If, as you say, you really truly cannot use readlines() here for some reason, just rewrite the for loop as a while loop that reads a line at a time until EOF. 如您所说,如果由于某种原因您确实真的不能在此处使用readlines() ,只需将for循环重写for while循环,即可一次读取一行直到EOF。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM