Exercise 3.1 (word count.py). Write a program that takes in a filename and strin
ID: 3700409 • Letter: E
Question
Exercise 3.1 (word count.py). Write a program that takes in a filename and string as input. Then print how many times that string appears inside the chosen file. If the file does not exist, continue asking for a filename until one is given that exists. Use your source code file as test input. Make sure to test files with that contain the same word multiple times. ? $ python3 word-count.py 2 Please enter a filename: wordcount.py 3 Please enter a string to search for: print The string print' appears 102 times in the file word count.pyExplanation / Answer
try:
print("Please enter a file name: ")
s=input()
print("Please enter a string to search for: ")
s1=input()
f=open(s,'r')
a=f.read().count(s1)
print("The string '",s1,"' appears ",a," times in the file '",s,"'")
except Exception as e:
print("No file found")
#this program checks for file to be read exists or not, if exists prints the number of occurances of string to be
# searched else prints "no file found"
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.