[英]Python - Delete Conditional Lines of Chat Log File
我正在尝试从聊天日志文件中删除对话,而仅分析其他人的数据。 当我像这样将文件加载到Python中时:
with open(chatFile) as f:
chatLog = f.read().splitlines()
这样加载数据(比示例更长):
'My Name',
'08:39 Chat data....!',
'Other person's name',
'08:39 Chat Data....',
'08:40 Chat data...,
'08:40 Chat data...?',
我希望它看起来像这样:
'Other person's name',
'08:39 Chat Data....',
'08:40 Chat data...,
'08:40 Chat data...?',
我正在考虑将if语句与正则表达式一起使用:
name = 'My Name'
for x in chatLog:
if x == name:
"delete all data below until you get to reach the other
person's name"
我无法使此代码正常工作,有什么想法吗?
我认为您误解了“正则表达式”的含义……这并不意味着您可以编写英语指令,而python解释器会理解它们。 要么就是使用伪代码,要么就无法调试。
如果您没有其他人的名字,我们可以假定它不是以数字开头。 假设所有非名称行都以数字开头,如您的示例所示:
name = 'My Name'
skipLines = False
results = []
for x in chatLog:
if x == name:
skipLines = True
elif not x[0].isdigit():
skipLines = False
if not skipLines:
results.append(x)
others = []
on = True
for line in chatLog:
if not line[0].isdigit():
on = line != name
if on:
others.append(line)
您可以使用re.sub
删除所有消息,其中第二个参数是空字符串,它是您的替换字符串。
假设每条聊天消息re.escape(yourname) + r',\\n(?:\\d.*?\\n)*'
时间戳开头的新行开始,并且没有人的名字可以以数字开头,则正则表达式模式为re.escape(yourname) + r',\\n(?:\\d.*?\\n)*'
的名字re.escape(yourname) + r',\\n(?:\\d.*?\\n)*'
应该匹配您所有的消息,然后可以将这些匹配替换为空字符串。
import re
with open(chatfile) as f:
chatlog = f.read()
yourname = 'My Name'
pattern = re.escape(yourname) + r',\n(?:\d.*?\n)*'
others_messages = re.sub(pattern, '', chatlog)
print(others_messages)
这可以从任意数量的用户正在聊天的任何聊天日志中删除任何用户的消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.