如何读取列表并使用数据创建字典?

时间:2018-07-26 23:50:00

标签: python

我要做的问题是编写一个程序,该程序读取文本文件的内容并创建一个字典,其中的键是单个唯一的单词,而值是一个包含文件中行号的列表。找到单词。 The following problem.到目前为止,我已经找到了如何读取文本文件的方法,但是不知道如何将数据传输到字典中。希望有人可以帮助谢谢!

with open('Kennedy.txt') as f:
    lines = f.readlines()
    lines = [line.rstrip('\n').lower() for line in open('Kennedy.txt')]
    lines.pop()
    print(lines)

3 个答案:

答案 0 :(得分:1)

非常简单

from collections import defaultdict

d = defaultdict(list) # initialize a dict with values as lists

with open('Kennedy.txt') as fin:
    for idx, line in enumerate(fin): # for index, line in file
        words = line.lower().split() # make it case insensitive
        for word in words: # for word in list of lower-case words
            d[word].append(idx) # append the value to the list

答案 1 :(得分:0)

使用enumerate产生行号,并将其附加到单词索引的字典列表中。

output = {}
with open('Kennedy.txt') as f:
    for i, l in enumerate(f.readlines(), 1):
        for w in l.lower().split():
            output.setdefault(w, []).append[i]

答案 2 :(得分:0)

尝试一下:

    words_dict = dict()

    with open('Kennedy.txt', 'r') as f:
        i = 0
        for line in f:
            i += 1
            for word in line.strip().split(' '):
                word = word.lower()
                if word not in words_dict.keys():
                    words_dict[word] = []
                words_dict[word].append(i)

    print(words_dict)