gpt4 book ai didi

python - 开始字数统计程序仅生成 python 中最后一行的输出

转载 作者:太空宇宙 更新时间:2023-11-03 18:48:01 24 4
gpt4 key购买 nike

我是一名初学者程序员,试图构建一个简单的程序。它应该计算文件中的每个单词,但正如我所写,它只计算文本的最后一行。

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)

list 变量重命名为 lst 是个好主意,因为 list 是一个内置变量,而且是一个覆盖它是个坏主意。对于 dict 也是如此,您不应该将其用作变量名称。

另一个好主意:使用 Counter对象来跟踪词频,这比手动更新字典的计数器值要容易得多。您创建和填充字典的整个代码块可以替换为:

from collections import Counter
d = Counter(lst) # notice the suggested variable names

关于python - 开始字数统计程序仅生成 python 中最后一行的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19042380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com