我需要编写一个 python 代码来读取文本文件(file.txt)的内容并计算每个句子的平均单词数。(假设文件包含许多句子,每行只有一个。)
我做了编码,我需要知道它是否可以通过另一种方式更有效。百万提前感谢。这是我的:
# This program reads contents of a .txt file and calulate
# the average number of words per sentence .
line_count=0
# open the file.txt for reading
content_file=open('file.txt','r')
# calculate the word count of the file
content=content_file.read()
words= content.split()
word_count=len(words)
# calculate the line count
for line in open('file.txt'):
line_count+=1
content_file.close()
# calculate the average words per line
average_words=word_count/line_count
# Display the result
print('The average word count per sentence is', int(average_words))