正则表达式输出计数
问题描述:
我想计算一个正在进行的数据集上的正则表达式搜索的输出,但由于某种原因,我的计数被大量关闭。我想知道我做错了什么,我怎么能得到一个正式的计数。我应该有大约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!
这里计数是在初始化过程中的列表,你不能增加一个列表object.Make计数= 0 – bigbounty
@bigbounty是的,谢谢我不相信我错过了。最后一个简单的问题是,这种方法会计算每个输出的数量,最后如何计算总数? – user7823345
@bigbounty我如何评论评论?你可以通过说count.append(1)来解释你的意思吗? – user7823345