使用循环计数一个单词

发布于 2025-01-26 09:22:26 字数 297 浏览 1 评论 0原文

我试图计算文件中的单词[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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

海拔太高太耀眼 2025-02-02 09:22:26
count = 0
with open('test.log', 'r') as logfile:
    lines = logfile.readlines()
    for line in lines:
        count += line.count('[error]')
print(count)
count = 0
with open('test.log', 'r') as logfile:
    lines = logfile.readlines()
    for line in lines:
        count += line.count('[error]')
print(count)
潜移默化 2025-02-02 09:22:26

我认为正在发生的是,循环在每行循环时都会打印每条线中有多少个错误。您可能想做的是在循环外有一个外部变量,该变量添加到以找到总和。

error_count = 0
with open(r'test.log') as logfile:
   for line in logfile:
        error_count += line.count('[error]')
   print("error" + str(error_count))

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.

error_count = 0
with open(r'test.log') as logfile:
   for line in logfile:
        error_count += line.count('[error]')
   print("error" + str(error_count))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文