2 回答

TA貢獻1816條經驗 獲得超4個贊
嘗試這個:
此解決方案的主要思想是解析日志的月份和年份,并將其用作data字典中的鍵?,F在,對于匹配相同月份和年份的每個日志,字典的值都會增加 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)
添加回答
舉報