0

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

2 回答 2

7

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 = ...扩展的可迭代解包,仅在 Python 3.x 中可用。

于 2013-06-17T17:22:27.683 回答
0
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,)
于 2013-06-17T17:21:00.460 回答