简体   繁体   English

读取文本文件并返回字典

[英]Read a text file and return a dictionary

I have some doubts with a python example. 我对python示例有些怀疑。

I want to have a function that receives a text file name as input and returns a dictionary in which each word, separated by space, is associated with a list with the number of the lines in which that word appears. 我想要一个函数,该函数接收文本文件名作为输入并返回一个字典,该字典中的每个单词(由空格分隔)与一个列表以及该单词在其中出现的行数相关联。

For example for this example: 例如此示例:

Example of python program.
Basic python program.

The result should be: 结果应为:

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

Im doing like below to read the text file, I have a test.txt file and I enter that test.txt file I don't see any results. 我在做下面的操作来读取文本文件,我有一个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:])
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)

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM