In: Computer Science
Write a python program that calculates the average number of words per sentence in the input text file. every sentence ends with a period (when, in reality, sentences can end with !, ", ?, etc.) and the average number of sentences per paragraph, where a paragraph is any number of sentences followed by a blank line or by the end of the text.
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.
#code
#reading name of file from user
file=input("Enter input file name: ")
#opening file, assuming file exists
file=open(file)
#declaring number of words, sentences and paragraphs to
0
words=0
sentences=0
paragraphs=0
#reading all lines from file to a list
lines=file.readlines()
#closing file
file.close()
#looping through each index in lines list
for i in range(len(lines)):
#removing the newline char from end of
current line
line=lines[i].strip()
#checking if line is empty (blank
line)
if
line=='':
#incrementing number
of paragraphs
paragraphs+=1
else:
#splitting the line
into a list of words by space or tab
words_in_line=line.split()
#looping through
each word in resultant list
for w in words_in_line:
#incrementing words count
words+=1
#if word ends with a period, incrementing sentences
if w.endswith('.'):
sentences+=1
#if this is the last
line and line is not empty (end of text),
#incrementing
paragraphs
if
i==len(lines)-1:
paragraphs+=1
#at the end, if any field is 0, displaying that the file is
empty
if paragraphs==0 or words==0
or sentences==0:
print("Empty file!")
else:
#otherwise finding the average words per
sentence
avg_words_per_sentence=words/sentences
#and average sentences per paragraph
avg_sentences_per_paragraph=sentences/paragraphs
#displaying results
print("Average number of words per
sentence:",avg_words_per_sentence)
print("Average number of sentences per
paragraph:", avg_sentences_per_paragraph)
#output
#screenshot of inp.txt file used in this program