In: Computer Science
Write a program in python that counts the number of words in President Abraham Lincoln’s Gettysburg Address from the file provided. Replace all instances of "nation" with country, and all instances of "we" with "Americans". Write the revised address to a new file
its for a txt file
f=open(input("Enter filename:"),'r')#open file in read
mode
l=list(f.readlines())
for i in range(len(l)):
l[i]=l[i][:-1]#remove new line characters
c=0
for i in l:
temp=i.split(" ")
c=c+len(temp)#get the number of words in each line and add to
c
temp=[]
print("The count is: ",c)#print total number of words
res=[]
for i in range(len(l)):
temp=l[i].split(" ")
for j in range(len(temp)):
if temp[j]=="nation":#check if word is nation and replace it
temp[j]="country"
if temp[j]=="we":#check if word is we and replace it
temp[j]="Americans"
res.append(' '.join(temp))#append the lines to list res
file=open("resultaddress.txt",'w')#open file to write
for i in res:
file.write(i+"\n")#write the data to file and close it
file.close()
Screenshots:
The screenshots are attached below for reference.
Please follow them for output and proper indentation.
Please upvote my answer. Thank you.
The input file provided is as follows.
The output resultant file that is generated by the program is as follows.