Answer:
See explaination
Explanation:
import os,string
def readfile(filename):
if os.path.isfile(filename) is not True:return None
line_number=1
word_dict={}
print('Text File to be analyzed: {}'.format(filename))
with open(filename,'r') as infile:
for line in infile.readlines():
words = line.strip().split()
for word in words:
word = word.strip(string.punctuation)
if word.strip()=='':continue
if word_dict.get(word)==None:
word_dict[word]=[line_number]
else:
line_number_list=word_dict.get(word)
line_number_list.append(line_number)
line_number+=1
return word_dict
def write_to_file(word_dict,filename):
with open(filename,'w') as outfile:
for word in sorted(word_dict.keys()):
outfile.write('{0}:\t\t{1}\n'.format(word,','.join([str(n) for n in word_dict.get(word)])))
def main():
filename='D:\\Word.txt'
output_filename='D:\\word_index.txt'
word_dict = readfile(filename)
if word_dict ==None:
print('Unable to read file {}'.format(filename))
else:
for word in sorted(word_dict.keys()):
print('{0}:\t\t{1}'.format(word,','.join([str(n) for n in word_dict.get(word)])))
write_to_file(word_dict,output_filename)
main()