简体   繁体   中英

Read a text file and return a dictionary

I have some doubts with a python example.

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.

 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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