Computer Science

Write a program to read a file 'Story.txt' and create another file, storing an index of 'Story.txt', telling which line of the file each word appears in. If word appears more than once, then index should-show all the line numbers containing the word.

Python Data Handling

2 Likes

Answer

Let the file "Story.txt" include the following sample text:

The cat sleeps
The dog barks
The cat jumps
The sun shines
word_index = {}
file = open('Story.txt', 'r')
line_number = 1
lines = file.readlines()
for line in lines:
    words = line.strip().split()
    for word in words:
        if word in word_index:
            word_index[word].append(str(line_number))
        else:
            word_index[word] = [str(line_number)]
    line_number += 1
file.close()

index_file = open('index.txt', 'w')
for word, line_numbers in word_index.items():
    line_numbers_str = ", ".join(line_numbers)
    index_file.write(word + ":" + line_numbers_str + "\n")
index_file.close()

The "index.txt" file includes following text:

The:1, 2, 3, 4
cat:1, 3
sleeps:1
dog:2
barks:2
jumps:3
sun:4
shines:4

Answered By

3 Likes


Related Questions