Python 从文件中读取字数并计算每句平均数的有效方法
我需要编写一个python代码,读取文本文件(file.txt)的内容,并计算每个句子的平均字数(假设该文件包含多个句子,每行仅一个) 我做了编码,我需要知道它是否能以另一种方式更有效。万分感谢。 这是我的:Python 从文件中读取字数并计算每句平均数的有效方法,python,file,word-count,line-count,Python,File,Word Count,Line Count,我需要编写一个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 read
# 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
我的建议是,不要使用for循环,而是使用“\n”分割内容并查找数组的长度 打开file.txt进行读取 content\u file=open('file.txt','r') 计算文件的字数 content=content\u file.read() word\u count=len(content.split()) 行\u count=len(content.split('\n')) content_file.close() 计算每行的平均单词数 平均单词数=单词数/行数 显示结果
print('每个句子的平均字数为',int(平均字数))由于我们一次只读取一次文件内容,下面的代码将是有效的
with open(r'C:\Users\lg49242\Desktop\file.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
平均值=总字数/行数
打印平均值