猿问

如何从文件创建字典?

我正在尝试编写一个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)]


MMMHUHU
浏览 168回答 2
2回答

红颜莎娜

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,)
随时随地看视频慕课网APP

相关分类

Python
我要回答