我需要编写一个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))
无需两次迭代文件。只需在您浏览行::
时更新计数lc, wc = 0, 0
with open('file.txt','r') as f:
for line in f:
lc += 1
wc += len(line.strip().split())
avg = wc / lc
我的建议是,而不是用于循环用' n'将内容分开并找到数组的长度。
打开file.txt供阅读
content_file = open('file.txt','r')
计算文件的单词计数
content = content_file.read()
word_count = len(content.split())
line_count = len(content.split(' n'))
content_file.close()
计算每行平均单词
平均_words = word_count/line_count
显示结果
print(''每句话的平均单词计数为',int(平均_words))
以下代码将是有效的,因为我们一次一次读取文件内容。
with open(r'C:Userslg49242Desktopfile.txt','r') as content:
lineCount = 0
Tot_wordCount = 0
lines = content.readlines()
for line in lines:
lineCount = lineCount + 1
wordCount = len(line.split())
Tot_wordCount += wordCount
avg = tot_wordcount/linecount
打印AVG