我正在尝试为 WhatsApp 的对话日志编写解析器。问题末尾的最小日志文件。
在这个日志中,有两种消息,普通的,语法是
date time: Name: Message
如您所见,Message
可以换行,名称可以包含 :
。
第二种消息是“事件”消息,可以是以下类型:
date time: Name joined
date time: Name left
date time: Name was removed
date time: Name changed the subject to “GroupName”
date time: Name changed the group icon
我试图写下一些正则表达式,但我遇到的困难有几个:如何处理多行消息,如何解析 Name
字段(因为在 :
上拆分不起作用),如何构建一个正则表达式来识别仅来自当前组中的发件人的消息,最后如何解析特殊消息(例如,解析搜索 joined as last word 这不是一个好主意)。
我如何解析这样的日志文件并将所有内容移动到字典中?
更准确地说,为了回答评论中的问题,我考虑的输出类似于嵌套字典: 在第一层中键是每个发送者,在第二层中区分“事件”(例如加入、离开等)和“消息”,并将所有内容作为元组列表。
>>>datab[Sender1]['Events']
>>>[('Joined',data1,time1),('Left',data2,time2]
>>>datab[Sender2]['Messages']
>>>[(data1,time1,Message1),(data2,time2,Message2)]
但如果您能想到更智能的格式,那就去做吧!
29/03/14 15:48:05: John Smith changed the subject to “Test”
29/03/14 16:10:39: John Smith joined
29/03/14 16:10:40: Person:2 joined
29/03/14 16:10:40: John Smith: Hello!
29/03/14 16:11:40: Person:2: some random words,
29/03/14 16:12:40: Person3 joined
29/03/14 16:13:40: John Smith: Hello!Test message with newline
Another line of the same message
Another line.
29/03/14 16:14:43: Person:2: Test message using as last word joined
29/03/14 16:15:57: Person3 left
29/03/14 16:17:16: Person3 joined
29/03/14 16:18:21: Person:2 changed the group icon
29/03/14 16:19:16: Person3 was removed
29/03/14 16:20:43: Person:2: Test message using as last word left
最佳答案
你可以使用这个模式:
(?P<datetime>\d{2}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2}): (?P<name>\w+(?::\s*\w+)*|[\w\s]+?)(?:\s+(?P<action>joined|left|was removed|changed the (?:subject to “\w+”|group icon))|:\s(?P<message>(?:.+|\n(?!\n))+))
为了处理多行消息,我禁止使用否定的先行连续换行符。但是,您可以通过在 \n
关于python - 解析 whatsApp 对话日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24629933/