阅读文本文件并返回字典

时间:2018-02-01 00:37:56

标签: python dictionary

我对python示例有些怀疑。

我希望有一个函数接收文本文件名作为输入,并返回一个字典,其中每个单词(用空格分隔)与一个列表相关联,该列表包含该单词出现的行数。

例如,对于此示例:

Example of python program.
Basic python program.

结果应为:

d['Example] = [1]
d['of'] = [1]
d['python']= [1,2]
d['program'] = [1,2]
d['Basic'] = [2]

我正如下面这样阅读文本文件,我有一个test.txt文件,我输入test.txt文件,我没有看到任何结果。

 with open(input("Enter Filename: "),'r') as inF:
    newDict = {}
    inF = open(input("Enter Filename: "),'r')
    for line in inF:
        splitLine = line.split()
        newDict[(splitLine[0])] = ",".join(splitLine[1:])

1 个答案:

答案 0 :(得分:3)

from collections import defaultdict

data = defaultdict(list)

with open('test.txt') as f:
    for cnt, line in enumerate(f, 1):
        for word in line.strip().split():
            data[word].append(cnt)

print(data)

输出:

'Example': [1], 
'of': [1], 
'python': [1, 2], 
'program.': [1, 2], 
'Basic': [2]