![](/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.