2 回答
TA贡献1816条经验 获得超4个赞
尝试这个:
此解决方案的主要思想是解析日志的月份和年份,并将其用作data字典中的键。现在,对于匹配相同月份和年份的每个日志,字典的值都会增加 1
data = {} # outside
for file in datafiles:
with open(file, "r", encoding="utf8") as infile:
for l in infile:
m = re.match(r'\d{2}/(\d{2})/(\d{4})', l)
if m:
key = '{}/{}'.format(m.group(1), m.group(2))
if key not in data.keys():
data[key] = 0
data[key] += 1
# printing
for k in data:
print '{}: {} messages'.format(k, data[k])
lines 参考日志文件中的每一行
TA贡献1799条经验 获得超9个赞
使用 collections.defaultdict
前任:
import re
from collections import defaultdict
result = defaultdict(int)
with open(file, "r", encoding="utf8") as infile:
for line in infile: #Iterate Each line
line = line.strip()
m = re.match("(\d{2}/(\d{2})/(\d{4}))", line) #Check if line starts with date
if m:
result["{}/{}".format(m.group(2), m.group(3))] += 1 #form month/year and get count.
print(result)
添加回答
举报