[英]Replace section of text with only knowing the beginning and last word using Python
[英]Beginning word counting program only produces output for the last line in python
我是一個初學者,試圖構建一個簡單的程序。 它應該計算文件中的每個單詞,但正如我所寫的那樣,它僅計算文本的最后一行。
tm = open('myfile.txt', 'r')
for line in tm:
line = line.replace ('\n', '')
line = line.strip()
line = line.translate(None, '!#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
line = line.lower()
line = line.split(' ')
list = line
dict ={}
for word in list:
dict[word]=1
if word in dict:
count = dict[word]
count += 1
dict[word] = count
else:
dict[word]=1
for word,count in dict.iteritems():
print word + ": " + str(count)
我的輸出是這個
about: 1
to: 1
subscribe: 1
hear: 1
new: 1
our: 1
newsletter: 1
email: 1
ebooks: 2
對於500頁的文檔,我們將不勝感激
將此行替換為您的代碼:
list = line # that's not how you add elements to a list!
與其他:
list.extend(line)
而這將會是重命名為一個好主意, lst
的list
變量,因為list
是內置的,這是一個壞主意,將其覆蓋。 與dict
相同,您不應將其用作變量名。
另一個好主意:使用Counter
對象來跟蹤單詞頻率,這比手動更新字典的計數器值容易得多。 您可以在此創建和填充字典的整個代碼塊替換為:
from collections import Counter
d = Counter(lst) # notice the suggested variable names
如Oscar所說,您應該將數組項添加到列表中,而不是替換它。 嘗試使用擴展而不是附加。
list.extend(line)
您可以一次將數組中的所有項目添加到列表中。
append用於將單個項目添加到列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.