正则表达式输出计数

Regex Output Count

我正在尝试计算我在数据集上进行的正则表达式搜索的输出,但由于某种原因,我的计数差了很多。我想知道我做错了什么以及如何获得官方统计。我应该有大约 1500 个匹配项,但我不断收到一条错误消息,提示“'int' 对象不可迭代”。

import re

with open ('Question 1 Logfile.txt' , 'r') as h:
    results = []
    count = []
    for line in h.readlines():
        m = re.search(r'(((May|Apr)(\s*)\w+\s\w{2}:\w{2}:\w{2}))', line)
        t = re.search(r'(((invalid)(\s(user)\s\w+)))',line)
        i = re.search(r'(((from)(\s\w+.\w+.\w+.\w+)))', line)
        if m and t and i:
            count += 1
            print(m.group(1),' - ',i.group(4),' , ',t.group(4))
            print(count)

您想在一系列循环迭代中增加满足条件的次数。这里的困惑似乎是如何做到这一点,以及要增加什么变量。

如 OP 和 OP 评论中所述,这是一个小示例,它反映了您遇到的困难。它是一个学习示例,但它也提供了几个解决方案选项。

count = []
count_int = 0

for _ in range(2):
    try:
        count += 1
    except TypeError as e:
        print("Here's the problem with trying to increment a list with an integer")
        print(str(e))

    print("We can, however, increment a list with additional lists:")
    count += [1]
    print("Count list: {}\n".format(count))

    print("Most common solution: increment int count by 1 per loop iteration:")
    count_int +=1
    print("count_int: {}\n\n".format(count_int))

print("It's also possible to check the length of a list you incremented by one element per loop iteration:")
print(len(count))

输出:

"""
Here's the problem with trying to increment a list with an integer: 
'int' object is not iterable

We can, however, increment a list with additional lists:
Count list: [1]

Most common is to increment an integer count by 1, for each loop iteration:
count_int: 1


Here's the problem with trying to increment a list with an integer: 
'int' object is not iterable

We can, however, increment a list with additional lists:
Count list: [1, 1]

Most common is to increment an integer count by 1, for each loop iteration:
count_int: 2


It's also possible to check the length of a list you incremented 
by one element per loop iteration: 
2
"""

希望对您有所帮助。祝学习顺利Python!