簡體   English   中英

匹配來自Python中WhatsApp日志的消息

[英]Match messages from WhatsApp log in python

我想提取與WhatsApp中的消息匹配的所有模式。 消息具有以下形式:

一行信息:

[19.09.17, 19:54:48] Marc: If the mean is not in the thousands, there's the problem

多行長消息:

[19.09.17, 19:54:59] Joe: > mean(aging$Population)
[1] 1593.577
Is what I get as solution

通過首先讀取文本文件行中的行,然后在不同的分隔符上拆分這些行,我能夠將其拆分為日期,時間,發件人和消息,但僅用於單行。 但是,這不適用於多行郵件。 現在,我正在嘗試使用正則表達式,使用它們可以獲取日期和時間,但是我仍在努力將消息的模式擴展到多行。

## reg expressions to match different things in the log
date = r'\[\d+\.\d+\.\d+,'
time = r'\d+\:\d+\:\d+]'
message = r':\s+.+\['
message = re.compile(message, re.DOTALL)

請注意,我的日志來自德語WhatsApp,這就是為什么日期有些不同的原因。 另外,我以和結束,以確保不會意外從郵件中獲得匹配項。

我想通過在[通常是下一行的開始處(結束,但是如果可以在新行的消息中找到它的話,可能並不那么健壯)來對消息模式做同樣的事情。

也許有一種更簡單的解決方案,但是(如您所見)我對正則表達式確實不好。

這是使用re.findall的常規正則表達式和解決方案:

msg = "[19.09.17, 19:54:48] Marc: If the mean is not in the thousands, there's the problem
    [19.09.17, 19:54:59] Joe: > mean(aging$Population)
    [1] 1593.577\nIs what I get as solution"

results = re.findall(r"\[(\d{2}\.\d{2}\.\d{2}), (\d{2}:\d{2}:\d{2})\] ([^:]+): (.*?)(?=\[\d{2}\.\d{2}\.\d{2}, \d{2}:\d{2}:\d{2}\]|$)", msg, re.MULTILINE|re.DOTALL)

for item in results:
    print "date: " + item[0]
    print "time: " + item[1]
    print "sender: " + item[2]
    print "message: " + item[3]

date: 19.09.17
time: 19:54:48
sender: Marc
message: If the mean is not in the thousands, there's the problem
date: 19.09.17
time: 19:54:59
sender: Joe
message: > mean(aging$Population)

該模式看起來很長而且很腫脹,剛好符合您所期望的WhatsApp消息的結構。 值得注意的是,該模式同時使用多行和DOT ALL模式。 對於可能跨越多行的消息,這是必需的。 當模式看到下一條消息的開始(特別是時間戳記)或看到輸入的結束時,它停止使用給定的消息。

劫持了上面的內容,以防萬一,我只是從Tim Biegeleisen裁剪了正則表達式

results = re.findall(r"\[(\d{2}\.\d{2}\.\d{2}), (\d{2}:\d{2}:\d{2})\] ([^:]+): (.*?)(?=\[\d{2}\.\d{2}\.\d{2}, \d{2}:\d{2}:\d{2}\])", msg, re.MULTILINE|re.DOTALL)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM