我正在尝试在匹配时更新子字符串的值。出于某种原因,我最终无法理解所有子字母都具有相同的值。
def (d,content):
for i in d:
for x in d[i]:
regex = re.compile(i + '.*.' + x + '.*')
for string in content:
if (bool(regex.match(string))) == True:
d[i][x] +=1
print("match")
我刚开始学习Python。我无法理解问题Update value of a nested dictionary of varying depth的答案中的逻辑。
下面是输入字典的样子。
{'Aug 1 03:46:0':
{'chronyd': 0, 'rsyslogd': 0, 'systemd': 0},
'Aug 1 03:56:4':
{'chronyd': 0, 'rsyslogd': 0, 'systemd': 0},
'Aug 1 04:01:0':
{'chronyd': 0, 'rsyslogd': 0, 'systemd': 0},
'Aug 1 04:06:0':
{'chronyd': 0, 'rsyslogd': 0, 'systemd': 0},
'Aug 1 05:01:0':
{'chronyd': 0, 'rsyslogd': 0, 'systemd': 0}}
content='''
Aug 1 03:46:01 localhost rsyslogd: [origin software="rsyslogd" swVersion="7.4.7" x-pid="880" x-info="http://www.rsyslog.com"] rsyslogd was HUPed
Aug 1 03:56:48 localhost chronyd[640]: Source 96.244.96.19 replaced with 96.126.105.86
Aug 1 04:01:01 localhost systemd: Started Session 7 of user root.
Aug 1 04:01:01 localhost systemd: Starting Session 7 of user root.
Aug 1 04:06:01 localhost systemd: Removed slice user-0.slice.
Aug 1 04:06:01 localhost systemd: Stopping user-0.slice.
Aug 1 05:01:01 localhost systemd: Created slice user-0.slice.
Aug 1 05:01:01 localhost systemd: Starting user-0.slice.
Aug 1 05:01:01 localhost systemd: Started Session 8 of user root.
Aug 1 05:01:01 localhost systemd: Starting Session 8 of user root.
'''
以下是我创建字典的方式。
uniq_time = sorted(set([" ".join([" ".join([x[0],x[1]]),x[2][:-1]]) for x in mlist]), key=str.lower)
uniq_processes = sorted(set([ x[4].split('[')[0] for x in mlist]), key=str.lower)
d = dict.fromkeys(uniq_time, dict.fromkeys(uniq_processes, 0))