[英]how to create a dictionary from a file?
I'm trying to write a Python code that will allow me to take in text, and read it line by line. 我正在尝试编写一个Python代码,该代码允许我输入文本并逐行读取。 In each line, the words just go into the dictionary as a key and the numbers should be the assigned values, as a list. 在每一行中,单词只是作为关键字进入字典,数字应作为分配的值(如列表)。 the file 'topics.txt' will be composed of hundreds of lines that have the same format as this: 文件“ 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
and so on.. i need to create dictionaries for each word for ex: Ideally, the name "grain" would be a key in the dictionary, and the values would be dict[grain]: [5,6,..]. 等等,等等。我需要为ex的每个单词创建词典:理想情况下,名称“ grain”将是字典中的键,而值将是dict [grain]:[5,6,..]。 similarly, "cocoa" would be another key and values would be dict[cocoa]:[1,..] Not much,but so far.. 类似地,“可可”将是另一个键,值将是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)]
http://docs.python.org/3/library/collections.html#collections.defaultdict http://docs.python.org/3/library/collections.html#collections.defaultdict
import collections
with open('topics.txt') as f:
d = collections.defaultdict(list)
for line in f:
value, *keys = line.strip().split('~')
for key in filter(None, keys):
d[key].append(value)
value, *keys = ...
is Extended Iterable Unpacking which is only available in Python 3.x. value, *keys = ...
是扩展的可迭代拆包 ,仅在Python 3.x中可用。
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,)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.