我有一個要保存為csv格式的WhatsApp消息文件。文件看起來像這樣:[04/02/2018,20:56:55] Name1:此聊天消息和通話現(xiàn)在已通過端到端加密進行保護。[04/02/2018,20:56:55]名稱1:Content1。更多內(nèi)容。[04/02/2018,23:24:44] Name2:Content2。我想將郵件解析為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)我在處理多行文本時遇到問題。(有時我會在消息中跳入新行-在這種情況下,該行中只有文本,應該是上一行的一部分。)我也對解析日期時間,發(fā)件人,和文字。我的代碼的結果是錯誤的,因為每一行都沒有所有條件(但正確地解析了日期,發(fā)件人,文本):---------------------------------------------------------------------------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。)
添加回答
舉報
0/150
提交
取消