Advertisements
Advertisements
Question
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.
Hint : Dictionary with key as word(s) can be used to solve this.
Code Writing
Advertisements
Solution
import re
from collections import defaultdict
def create_word_index():
index = defaultdict(set)
with open("Story.txt", "r") as file:
for line_number, line in enumerate(file, start=1):
words = re.findall(r"[A-Za-z]+", line.lower())
for word in words:
index[word].add(line_number)
with open("StoryIndex.txt", "w") as file:
for word in sorted(index):
line_numbers = ", ".join(
str(number) for number in sorted(index[word])
)
file.write(f"{word}: {line_numbers}\n")
create_word_index()
A set prevents the same line number from being repeated when a word occurs more than once on that line.
shaalaa.com
Is there an error in this question or solution?
