如何计算文本文件中的行数?

时间:2016-05-05 01:58:33

标签: python

对于python我有一个任务,我必须计算文本文件中的单词数,并显示每个句子的平均单词数。然而,平均字数总是变为一。

文本文件是

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()

4 个答案:

答案 0 :(得分:0)

 for line in line_list:
        num_lines = num_lines + 1

^那是错的。 line_list是单词 - 您正在添加一行"行"对于每个单词,而不是每行一次。 num_lines = num_lines + 1循环中应该只有一个while

答案 1 :(得分:0)

好吧,既然这是作业,我只会给出提示。

分裂做什么? 什么是“for y in y:”吗?

确保正确计算单词和行。

答案 2 :(得分:0)

更好的方法是:

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)

答案 3 :(得分:0)

您的任务是确定每个句子的平均字数。句子以句号/句号字符(以及其他句号,例如问号)终止并且可以跨行,或者在一行上可以有多个句子。可能是您的样本数据是您需要处理的所有情况,在这种情况下,您假设每行有一个句子是正确的。如果不是,那么您需要特别对待'.''?'等。

针对特定问题,平均值为1,因为total_linestotal_words将始终相同。这是因为线条和单词的处理方式相同。

您不需要此代码,因为它实际上是计算单词,而不是行:

for line in line_list:
    num_lines = num_lines + 1

你可以改变

total_lines = total_lines + num_lines

total_lines = total_lines + 1

此外,当您使用Python 2时,平均计算将使用整数除法,即它将截断结果。您可以通过将其中一个值转换为float来强制浮点除法:

average = float(total_words) / total_lines
相关问题