69.4k views
4 votes
If you have downloaded this book's source code from the companion Web site, you will find a file named text.txt in the Chapter 12 folder. (The companion Web site is at www.pearsonhighered/gaddis.) The text that is in the file is stored as on sen- tence per line. Write a program that reads the file's contents and calculates the average of words per sentence.

1 Answer

4 votes

Answer:

Step-by-step explanation:

The following python code loops through each line within a file called text.txt and counts all the words, then it divides this count by the number of sentences in the text file. Finally, output the average number of words per sentence.

f = open("text.txt", "r")

all_words = 0

sentences = 0

for x in f:

list = x.split(' ')

all_words += len(list)

sentences += 1

average = all_words / sentences

print("There are an average of " + str(average.__round__()) + " words in each sentence.")

If you have downloaded this book's source code from the companion Web site, you will-example-1
User PurpleDiane
by
4.2k points