【问题标题】:Parsing WhatsApp messages: how to parse multiline texts解析 WhatsApp 消息:如何解析多行文本
【发布时间】:2018-07-25 19:57:19
【问题描述】:

我有一个 WhatsApp 消息文件,我想将其保存为 csv 格式。文件如下所示:

[04/02/2018, 20:56:55] Name1: ‎此聊天和通话的消息现在 通过端到端加密保护。
[04/02/2018, 20:56:55] 名称 1:内容 1。
更多内容。
[04/02/2018, 23:24:44] 名称 2:内容 2。

我想将消息解析为date, sender, text 列。我的代码:

with open('chat.txt', "r") as infile, open("Output.txt", "w") as outfile:
    for line in infile:
        date = datetime.strptime(
            re.search('(?<=\[)[^]]+(?=\])', line).group(), 
            '%d/%m/%Y, %H:%M:%S')
        sender = re.search('(?<=\] )[^]]+(?=\:)', line).group()
        text = line.rsplit(']', 1)[-1].rsplit(': ', 1)[-1]

        new_line = str(date) + ',' + sender + ',' + text
        outfile.write(new_line)

我在处理多行文本时遇到问题。 (我有时会在消息中跳入新行 - 在这种情况下,我在该行中只有应该是前一行的一部分的文本。) 我也对解析日期时间、发件人和文本的更多 Pythonic 方式持开放态度。 我的代码的结果是错误的,因为每一行都没有所有标准(但正确解析日期、发件人、文本):

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-33-efbcb430243d> in <module>()
      3     for line in infile:
      4         date = datetime.strptime(
----> 5             re.search('(?<=\[)[^]]+(?=\])', line).group(),
      6             '%d/%m/%Y, %H:%M:%S')
      7         sender = re.search('(?<=\] )[^]]+(?=\:)', line).group()

AttributeError: 'NoneType' object has no attribute 'group'

想法:也许使用 try-catch,然后以某种方式仅附加文本行? (听起来不像 Pythonic。)

【问题讨论】:

  • 发件人的正则表达式:(?&lt;=\] )[^]]+(?=\:) - 我认为您应该将其更改为 (?&lt;=\] )[^]]+?(?=\:)
  • date 的正则表达式看起来不错(demo::regex101.com/r/TXqxPK/1)。确保该行不为空或其他内容
  • 两个正则表达式都可以正常工作(我打印了输出)。问题是我有时会在我的消息中使用换行命令 - 在这种情况下,我的行中只有文本应该是前一行的一部分。
  • 我认为你应该读一行。检查它是否以[ 开头。如果是,则意味着读取的行是一条新消息。如果不是,这意味着读取的行是上一条消息内容的一部分。所以将它附加到上一条消息的内容中
  • 创建一个临时变量,比如x,并将其设置为空字符串。然后打开输入流。读取一行,检查第一个非空白字符是否为[。如果是,则首先将x 刷新到输出流上。然后将x 设置为str(date) + ',' + sender + ',' + text。如果第一个非空白字符不是[,则只需将x 设置为x + line(不输出任何内容)

标签: python regex parsing


【解决方案1】:

这里应该可以将额外的文本附加到上一行。

这是检查正则表达式是否失败,在这种情况下,只需将行写入文件而不使用换行符\n,因此它只是附加到文件中的上一行。

start = True

with open('chat.txt', "r") as infile, open("Output.txt", "w") as outfile:
    for line in infile:
        time = re.search(r'(?<=\[)[^]]+(?=\])', line)
        sender = re.search(r'(?<=\] )[^]]+(?=\:)', line)
        if sender and time:
            date = datetime.strptime(
                time.group(),
                '%d/%m/%Y, %H:%M:%S')
            sender = sender.group()
            text = line.rsplit(r'].+: ', 1)[-1]
            new_line = str(date) + ',' + sender + ',' + text
            if not start: new_line = '\n' + new_line
            outfile.write(new_line)
        else:
            outfile.write(' ' + line)
        start = False

看起来即使正则表达式有效,您也没有在文件中写入新行,所以我也添加了。

【讨论】:

  • 我只需要从文本变量中删除 '\n' ,然后您的解决方案就起作用了。谢谢。
猜你喜欢
  • 1970-01-01
  • 2014-04-21
  • 2018-01-03
  • 2019-11-11
  • 2010-11-05
  • 2014-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多