In: Computer Science
A sentence can end with full-stop, question mark, or an exclamation mark. Spaces precede and follow a word.
Write a Python program to perform the following tasks:
Code:
#ask the user to enter a filename
filename = input("Enter a filename: ")
#open the file name for reading
with open(filename, "r") as file:
#initialize variables
sentences = 0
words = 0
#iterate each line in the file object
for line in file:
sentences += line.count(".") #count the period symbols in line and
add it to sentences
sentences += line.count("!") #count the exclamation symbols in line
and add it to sentences
sentences += line.count("?") #count the question mark symbols in
line and add it to sentences
words += len(line.split(" ")) #split the line with respect to
spaces and add the lenght of the resulting list to words
print("Sentences = {}".format(sentences)) #print count of
sentences
print("Words = {}".format(words)) #print count of words
Code in the image:
Output:
Contents of sample file: sun.txt
This is sentence one. This is sentence two.
How are you? Great!
Haha! I am fine.