使用循环计数一个单词
我试图计算文件中的单词[error]
在文件中。 这就是我的尝试:
with open(r'test.log') as logfile:
for line in logfile:
error = line.count('[error]')
print(error)
此结果的结果列表:
0
1 1
1
0
1
等。 我希望结果是“错误10”或单词发生多少次
Im trying to count how many time the word [error]
is in a file.
This is how my attempt is looking:
with open(r'test.log') as logfile:
for line in logfile:
error = line.count('[error]')
print(error)
The outcome of this result a list like this:
0
1
1
0
1
etc.
I want the outcome to be "Error 10" or how many times the word occur
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为正在发生的是,循环在每行循环时都会打印每条线中有多少个错误。您可能想做的是在循环外有一个外部变量,该变量添加到以找到总和。
What I believe is happening is the loop is printing how many errors are in each line every time it loops. What you might want to do is have an external variable outside the loop that the loop adds to to find the total sum.