![](/img/trans.png)
[英]How to count number of lines in a file, between the values that repeat in a text file
[英]How do I count the number of lines in a text file?
对于python,我需要执行一项作业,其中必须计算文本文件中的单词数并显示每个句子的平均单词数。 但是,平均单词数总是总为1。
文本文件是
Hello
How are you
I am fine
Have a good day
Bye
这是代码
def main():
num_words = 0
total_words = 0
total_lines = 0
in_file = open("text.txt", "r")
line = in_file.readline()
while line != "":
num_words = 0
num_lines = 0
line_list = line.split()
for word in line_list:
num_words = num_words + 1
for line in line_list:
num_lines = num_lines + 1
total_words = total_words + num_words
total_lines = total_lines + num_lines
average = total_words / total_lines
line = in_file.readline()
print "Total words: ", total_words
print "Average number of words per sentence: ", average
in_file.close()
main()
for line in line_list:
num_lines = num_lines + 1
^那是错误的。 line_list
是单词-您要为每个单词添加一个“行”,而不是每行添加一次。 while
循环内只能有一个num_lines = num_lines + 1
。
好吧,由于这是家庭作业,因此我仅给出提示。
拆分做什么? “对于y中的x:”有什么作用?
确保正确计数单词和行数。
一个更好的方法是:
f = open('in_file.dat')
num_lines = 0
tot_words = 0
for line in f:
num_lines += 1
tot_words += len(line.split())
average = tot_words / num_lines
print(average)
您的任务是确定每个句子的平均单词数。 句子以句号/句号(以及其他字符,例如问号)终止,并且可以跨行,或者一行上可以有多个句子。 您的样本数据可能只是您需要处理的情况,在这种情况下,您假设每行只有一个句子是正确的。 如果不是,那么您需要处理'.'
, '?'
等等。
解决特定问题时,由于total_lines
和total_words
始终相同,因此平均值为1。 这是因为对行和单词进行同等对待。
您不需要此代码,因为它实际上是在计算单词而不是行:
for line in line_list:
num_lines = num_lines + 1
你可以改变
total_lines = total_lines + num_lines
至
total_lines = total_lines + 1
另外,当您使用Python 2时,平均计算将使用整数除法,即它将截断结果。 您可以通过将值之一强制转换为浮点数来强制进行浮点除法:
average = float(total_words) / total_lines
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.