![](/img/trans.png)
[英]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.