我正在尝试读取一个txt文件并从文本创建一个字典。txt文件示例如下:
John likes Steak
John likes Soda
John likes Cake
Jane likes Soda
Jane likes Cake
Jim likes Steak
我想要的输出是一个以名称为键的字典,“likes”是各个值的列表:
{'John':('Steak', 'Soda', 'Cake'), 'Jane':('Soda', 'Cake'), 'Jim':('Steak')}
我不断遇到错误,将我的精简单词添加到列表中,并尝试了几种不同的方法:
pred = ()
prey = ()
spacedLine = inf.readline()
line = spacedLine.rstrip('\n')
while line!= "":
line = line.split()
pred.append = (line[0])
prey.append = (line[2])
spacedLine = inf.readline()
line = spacedLine.rstrip('\n')
还有:
空间线=inf.readline文件()
line = spacedLine.rstrip('\n')
while line!= "":
line = line.split()
if line[0] in chain:
chain[line[0] = [0, line[2]]
else:
chain[line[0]] = line[2]
spacedLine = inf.readline()
line = spacedLine.rstrip('\n')
有什么想法吗?你知道吗
你的输入是一系列的序列。首先解析外部序列,然后解析每个项。你知道吗
你的外部序列是:
假设
f
是包含数据的打开文件。阅读每个语句并返回它们的列表:注意,上面的函数接受更广泛的语法:它允许在非空行之间任意多个空行,并且一行中有两个非空行。但它接受任何正确的输入。你知道吗
然后,您的语句是一个三元组:
X likes Y
。通过用空格分割它并检查结构来解析它。结果是一对正确的(x, y)
。你知道吗为每个语句列出一个对的列表:
现在需要按键对值进行分组。让我们使用
defaultdict
,它为任何新键提供默认值:所以这里
the_answer
是您需要的,只是它使用列表作为dict值而不是元组。这一定足够你理解你的作业了。你知道吗这样就可以了。你知道吗
在这里,我们遍历
f.readlines
f
作为file对象,并在每一行上使用split的第一部分作为键,split的最后一部分作为值来填充字典这样就可以了(无需先将整个文件读入内存):
输出:
或者,为了稍微简化一些,您可以使用一个临时的
collections.defaultdict
:相关问题 更多 >
编程相关推荐