将从 python 字典中提取的信息写入文件

Writing extracted information from python dictionary to a file

我有以下代码:

import os
import sys
import re
import glob
import datetime
import subprocess
from functions import *

event_dict = {1102: 0, 4611: 0,  4624: 0, 4634: 0, 4648: 0, 4661: 0, 4662: 0, 4663: 0, 4672: 0, 4673: 0, 4688: 0, 4698: 0, 4699: 0, 4702: 0, 4703: 0, 4719: 0, 4732: 0, 4738: 0, 4742: 0, 4776: 0, 4798: 0, 4799: 0, 4985: 0, 5136: 0, 5140: 0, 5142: 0, 5156: 0, 5158: 0}

event_IDs = [1102,4611,4624,4634,4648,4661,4662,4663,4672,4673,4688,4698,4699,4702,4703,4719,4732,4738,4742,4776,4798,4799,4985,5136,5140,5142,5156,5158]
iterations = 0


def finding_matched_events():

        with open('/home/user/CI5235_K1715142_Gary/CI5235_Logs/analyse_log_28_Feb_2021_11:22:05.txt', 'r') as logfile:
                for line in logfile:
                        if 'Matched' in line:

                                events = re.findall('\d+', line)

                                event_dict[int(events[0])] = event_dict[int(events[0])] + 1



 finding_matched_events()
   print(event_dict)

def log_output():   #Function to Print out event ID and count information and save to log file

        with open('/home/user/CI5235_K1715142_Gary/CI5235_Logs/visdata_log_' + timeStamp + '.txt', 'a') as f :

以上代码returns: {1102: 15, 4611: 2, 4624: 46, 4634: 1, 4648: 6, 4661: 19, 4662: 33, 4663: 114, 4672: 12, 4673: 2, 4688: 35, 4698: 2, 4699: 2, 4702: 4, 4703: 1, 4719: 8, 4732: 2, 4738: 5, 4742: 4, 4776: 7, 4798: 2, 4799: 1, 4985: 2, 5136: 42, 5140: 6, 5142: 1, 5156: 92, 5158: 14}调用函数并打印时event_dict.

**然后我正在编写另一个函数 log_ouput,我在其中使用提取的数据并尝试查看是否可以让该数据以特定的方式显示方式,但我不太确定如何实现它。我将如何以如下方式编写上面提取的数据:

事件ID:1102 事件 Count:15

事件ID:4611 事件 Count:2

事件ID:4624 事件 Count:46

事件ID:4634 事件 Count:1

事件ID:4648 事件 Count:6

等等……

我对编码还很陌生,使用 Python3、Linux Mint 和 VisualStudio

代码会写出你的字典:

event_dict = {1102: 15, 4611: 2, 4624: 46, 4634: 1,
              4648: 6, 4661: 19, 4662: 33, 4663: 114,
              4672: 12, 4673: 2, 4688: 35, 4698: 2,
              4699: 2, 4702: 4, 4703: 1, 4719: 8,
              4732: 2, 4738: 5, 4742: 4, 4776: 7,
              4798: 2, 4799: 1, 4985: 2, 5136: 42,
              5140: 6, 5142: 1, 5156: 92, 5158: 14}

fbase = '/home/user/CI5235_K1715142_Gary/CI5235_Logs/visdata_log_'
with open(fbase + timeStamp + '.txt', 'a') as f:
    for k,v in event_dict.items():
        print(f"Event ID:{k} Event Count:{v}", file=f)
# Event ID:1102 Event Count:15
# Event ID:4611 Event Count:2
# ...
 with open('/home/user/CI5235_K1715142_Gary/CI5235_Logs/visdata_log_' + timeStamp + '.txt', 'a') as f :
    for key in event_dict:
        f.write("Event ID:{} Event Count:{}".format(key, event_dict[key]))