[英]How to create a Python dictionary from data imported from a text file?
[英]How to create a dictionary from a text file in python?
我想从python中的文本文件创建字典。 我的文本文件是:
John Doe
Apples
Bananas
Oranges
Jane Dear
Apples
Bananas
Peaches
文本文件的格式为:
Name
Fruit
Fruit
.....
Fruit
empty line
Name
Fruit
.....
我想返回一个字典,其中以水果为键,名称为值,例如:
{"Apples":["John Doe", "Jane Dear"], "Bananas":["John Doe", "Jane Dear"], "Peaches":["Jane Dear"], "Oranges":["John Doe"]}
我不确定如何格式化文本文件。 提前致谢!
编辑:到目前为止我做了什么
def common(text):
x = open(text, "r")
a = {}
b = []
line = x.readline()
while line != "":
b.append(line)
line = courses.readline()
return b
def create_dict(lst):
a = []
b = {}
names = []
fruits = []
while lst != []:
if " " in lst[1]:
names += lst[1]
else:
fruits += lst[1]
这是我迷路的地方...
您可以使用一些方便的工具(例如itertools.groupby
和collections.defaultdict
:
from collections import defaultdict
from itertools import groupby
with open('work/test.txt') as f:
d = [
[s.strip() for s in g]
for k, g in groupby(f, key=lambda l: bool(l.strip())) if k
]
# [['John Doe', 'Apples', 'Bananas', 'Oranges'], ['Jane Dear', 'Apples', 'Bananas', 'Peaches']]
dd = defaultdict(list)
for l in d:
for fruit in l[1:]:
dd[fruit].append(l[0])
dd
# {'Apples': ['John Doe', 'Jane Dear'], 'Bananas': ['John Doe', 'Jane Dear'], 'Peaches': ['Jane Dear'], 'Oranges': ['John Doe']}
条件理解基于是否为空的属性将文件中的行分为几组,然后仅接受非空行的组( if k
)。 随后使用defaultdict
可以避免一些坎code的代码来检查密钥是否已经存在。
文本文件的格式需要更多的清晰度。 为了这个答案,我假设文本文件的格式是这样的。
NAME_1
FRUIT_1
FRUIT_2
FRUIT_3
NAME_2
FRUIT_1
FRUIT_2
FRUIT_3
.
.
NAME_3
.
.
.
现在,如果是这种情况,即,在水果的名称之后总是有一个双行换行符('\\ n \\ n'),并且该序列始终以人员的名称开头,那么这是一种填充此词典的方法。
with open('/path/to/file', 'r') as handle:
text = handle.read()
text = text.split('\n\n')
result = dict()
for item in text:
item = item.split('\n')
for fruit in item[1:]:
if fruit in result.keys():
result[fruit].append(item[0])
else:
result[fruit] = [item[0]]
希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.