我正在尝试编写一个 Python 代码,它允许我接收文本并逐行阅读。在每一行中,单词只是作为键进入字典,数字应该是分配的值,作为一个列表。文件“topics.txt”将由数百行组成,格式与此相同:
1~cocoa
2~
3~
4~
5~grain~wheat~corn~barley~oat~sorghum
6~veg-oil~linseed~lin-oil~soy-oil~sun-oil~soybean~oilseed~corn~sunseed~grain~sorghum~wheat
7~
8~
9~earn
10~acq
等等..我需要为ex的每个单词创建字典:理想情况下,名称“grain”将是字典中的键,值将是dict [grain]:[5,6,..]。同样,“可可”将是另一个键,值将是 dict[cocoa]:[1,..] 不多,但到目前为止..
with open("topics.txt", "r") as fi: # Data read from a text file is a string
d = {}
for i in fi.readlines():
temp = i.split()
#i am lost here
num = temp[0]
d[name] = [map(int, num)]