如何移除DataFrame中对话记录开头的无效内容?
问题
我有一个大型DataFrame,其中包含一列对话记录(Transcript),需要移除对话开头的无效消息——比如用户输入的hi或hello这类内容,同时要连带移除对应的机器人回复。
对话记录示例:
"User : Hello \nBot : Hi there. \nUser : Order status.\nBot : Your order status is your orders tab. \nUser : representative.""User : Agent please.\nBot : Waiting time is longer than usual."
期望输出:
"User : Order status.\nBot : Your order status is your orders tab. \nUser : representative.""User : Agent please.\nBot : Waiting time is longer than usual."
第二条对话未改动,因为其中不含hi或hello。
我当前尝试的代码:
df['Transcript'].str.split('\User').str.contains('hi|hello')
解决方案
可以用正则表达式结合str.replace()方法精准匹配并移除开头的无效对话段:
import pandas as pd import re # 定义正则模式:匹配开头的用户问候(hi/hello,不区分大小写)及对应的机器人回复 pattern = r'^User\s*:\s*(hi|hello)\s*\nBot\s*:\s*.+\s*\n' # 替换匹配到的无效内容为空字符串 df['Transcript'] = df['Transcript'].str.replace(pattern, '', flags=re.IGNORECASE)
模式说明
^:锚定字符串开头,确保只处理开头的无效对话User\s*:\s*:匹配User :格式,允许冒号前后有任意空白字符(hi|hello):匹配目标问候词,支持hi或hello\s*\n:匹配问候行末尾的空白字符和换行符Bot\s*:\s*.+\s*\n:匹配完整的机器人回复行,.+覆盖回复内容,最后匹配换行符
如果对话开头存在连续多轮问候(比如用户连续发hi/hello,机器人多次回复),可以改用以下模式一次性移除所有连续无效对话:
pattern = r'^((User\s*:\s*(hi|hello)\s*\nBot\s*:\s*.+\s*\n)+)'
内容的提问来源于stack exchange,提问作者Tal1992
相关产品推荐
相关产品推荐

