我是一个尝试构建一个简单程序的初学者程序员。它应该计算文件中的每个单词,但正如我所写的,它只计算最后一行文本。
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 页的文档,任何帮助表示赞赏