【问题标题】:Parsing multi-line whatsapp text with python not working用python解析多行whatsapp文本不起作用
【发布时间】:2019-08-18 06:01:03
【问题描述】:

我正在尝试准备一个 whatsapp 文件进行分析。我需要将它分为三列:时间、名称和消息。该文本包含对话中带有换行符的一些消息。当我将它加载到数据框中时,这些消息显示为它们自己的行而不是一条消息的一部分。

4/16/19, 15:22 - ‪+254 123 123‬: Hi my T. L

4/16/19, 15:22 - ‪+254 123 124‬: Was up

4/17/19, 06:28 - member: Hi team details are Thursday 18 April, 

Venue: Hilton Hotel

Time: 07:30am

Come on time team!

4/17/19, 12:17 - member: Hi guys

4/17/19, 12:18 - member: How many are coming tomorrow?

我尝试过使用两种方法:

  1. 直接使用正则表达式直接解析,如stackoverflow 和this 博客上的hereherethis 博客上的这些解决方案所示

  2. 间接通过创建一个文件,将这些多行消息编译成一行,如发现 here

这两种方法都失败了:( 我最喜欢的是第二种方法,只是因为您能够创建一个也可以被其他平台使用的文件,例如excel,画面...

对于方法 2:

import re
from datetime import datetime

start = True

with open('test.txt', "r", encoding='utf-8') as infile, open("output.txt", "w", encoding='utf-8') as outfile:
    for line in infile:
        time = re.search(r'\d\d\/\d\d\/\d\d,.(24:00|2[0-3]:[0-5][0-9]|[0-1][0-9]:[0-5][0-9])', line)
        sender = re.search(r'-(.*?):', line)
        if sender and time:
            date = datetime.strptime(
                time.group(),
                '%m/%d/%Y, %H:%M')
            sender = sender.group()
            text = line.rsplit(r'].+: ', 1)[-1]
            new_line = str(date) + ',' + sender + ',' + text
            if not start: new_line =  new_line
            outfile.write(new_line)
        else:
            outfile.write(' ' + line)
        start = False

我希望我终于不再得到:

4/17/19, 06:28 - member: Hi team details are Thursday 18 April, 

Venue: Hilton Hotel

Time: 07:30am

Come on time team!

然后得到:

4/17/19, 06:28 - member: Hi team details are Thursday 18 April, Venue: Hilton Hotel Time: 07:30am Come on time team!

此外,将其作为数据框输出,并正确完成日期时间、成员和消息。

【问题讨论】:

    标签: python regex parsing whatsapp


    【解决方案1】:

    正则表达式

    您将需要以下正则表达式:

    ^(\d{1,2})\/(\d{1,2})\/(\d\d), (24:00|2[0-3]:[0-5][0-9]|[0-1][0-9]:[0-5][0-9]) - (\S[^:]*?): (.*)$
    

    在线测试正则表达式in sandbox.

    代码

    接收到的数据形成一个 DateFrame 的对象。 最后,例如,将 DateFrame 对象保存在 CSV 文件中。

    import re
    from datetime import datetime
    import pandas as pd
    
    with open('test.txt', "r", encoding='utf-8') as infile:
        outputData = { 'date': [], 'sender': [], 'text': [] }
        for line in infile:
            matches = re.match(r'^(\d{1,2})\/(\d{1,2})\/(\d\d), (24:00|2[0-3]:[0-5][0-9]|[0-1][0-9]:[0-5][0-9]) - ((\S[^:]*?): )?(.*)$', line)
            if matches:
              outputData['date'].append(
                datetime(
                  int(matches.group(3))+2000,
                  int(matches.group(1)),
                  int(matches.group(2)),
                  hour=int(matches.group(4)[0:2]),
                  minute=int(matches.group(4)[3:])
                ))
              outputData['sender'].append(matches.group(6) or "{undefined}")
              outputData['text'].append(matches.group(7))
    
            elif len(outputData['text']) > 0:
              outputData['text'][-1] += "\n" + line[0:-1]
    
        outputData = pd.DataFrame(outputData)
        outputData.to_csv('output.csv', index=False, line_terminator='\n', encoding='utf-8')
    

    在线测试完整in sandbox.

    【讨论】:

    • 嘿 Uriy,你是摇滚明星!只有一个问题。我有一行以括号file.jpg (file attached) 结尾。不知何故,它选择了下一行,并且都出现在同一条消息中,例如file.jpg (file attached) 4/22/19, 09:30 - Person changed this group's icon。我怀疑它与正则表达式有关......
    • 嘿,@Sam!这是因为4/22/19, 09:30 - Person changed this group's icon 行中没有定义的发件人。这似乎是某种系统消息。可以用sender = {undefined}标记。我会更正正则表达式和算法。
    • 答案已更新,以考虑新的示例源消息字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    相关资源
    最近更新 更多