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
Write a program to accept string/sentences from the user till the user enters “END” to. Save the data in a text file and then display only those sentences which begin with an uppercase alphabet.
Write a function to insert a sentence in a text file, assuming that text file is very big and can't fit in computer's memory.
Write a program to accept a filename from the user and display all the lines from the file which contain Python comment character '#'.
Reading a file line by line from the beginning is a common task. What if you want to read a file backward ? This happens when you need to read log files. Write a program to read and display content of file from end to beginning.