73.9k views
2 votes
Assume the file text.txt contains one sentence per line. Write a program that reads the file's contents and prints the average number of words per sentence.

Write in Python
8.6

1 Answer

4 votes

Answer:

Here's a Python program that reads the file "text.txt" line by line, counts the number of words in each line, and calculates the average number of words per sentence:

with open('text.txt', 'r') as file:

lines = file.readlines()

word_count = 0

sentence_count = len(lines)

for line in lines:

words = line.split()

word_count += len(words)

average_words_per_sentence = word_count / sentence_count

print("Average words per sentence: ", average_words_per_sentence)

This program first opens the file "text.txt" in read mode and reads all the lines into a list called lines. Then, it initializes two variables: word_count to keep track of the total number of words in all the sentences, and sentence_count to keep track of the number of sentences in the file.

Next, the program iterates through each line in lines, splits the line into words using the split() method, and adds the number of words to word_count.

Finally, the program calculates the average number of words per sentence by dividing word_count by sentence_count, and prints the result.

Note that this program assumes that each sentence is on a separate line in the file "text.txt". If the sentences are not separated by line breaks, you may need to modify the program to split the text into sentences using a different approach.

User Bladefury
by
8.7k points