user9297268
user9297268

Reputation:

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:])

Upvotes: 0

Views: 1038

Answers (1)

Vlad Bezden
Vlad Bezden

Reputation: 89705

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]

Upvotes: 3

Related Questions