我正在尝试编写一个Python代码,该代码将允许我输入文本并逐行读取。在每一行中,单词只是作为关键字进入字典,数字应作为分配的值(如列表)。文件“ topics.txt”将由数百行格式相同的行组成:1~cocoa2~3~4~5~grain~wheat~corn~barley~oat~sorghum6~veg-oil~linseed~lin-oil~soy-oil~sun-oil~soybean~oilseed~corn~sunseed~grain~sorghum~wheat7~8~9~earn10~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)]
2 回答

红颜莎娜
TA贡献1842条经验 获得超12个赞
with open("topics.txt", "r") as file: # Data read from a text file is a string
dict = {}
for fullLine in file:
splitLine = fullLine.split("~")
num = splitLine[0]
for name in splitLine[1:]:
if name in dict:
dict[name] = dict[name] + (num,)
else
dict[name] = (num,)
添加回答
举报
0/150
提交
取消