从文本 Python 中删除括号中的时间戳

问题描述

我想删除以下示例文本数据中括号中的所有时间戳

输入:

特工:我能帮你吗? ( 3s ) 顾客: 谢谢 ( 40s ) 顾客: 我 有一个关于 X 的问题。 ( 8m 1s ) 特工:我可以在这里提供帮助。登录这个 网站(记得用你的新密码)(11m 31s)

预期输出

特工:我能帮你吗?客户:谢谢 客户:我有个问题 关于 X。 特工:我可以在这里帮忙。登录本网站(记得使用 您的新密码)

我尝试了 re.sub(r'\(.*?\)','',data) 但它没有工作,因为它删除了括号中的所有内容。如果不是时间戳,我想将内容保留在括号中,例如,我想在输出中保留“(记住使用您的新密码)”。

对正则表达式还很陌生,所以希望我能在这里得到一些指导。谢谢!

解决方法

\(\s(\d{1,2}[smh]\s)+\)

仅供参考:.* 匹配除行终止符之外的所有内容。

,

不是正则表达式,也许效率不高,但字符串方法可以:

spam = "Agent: Can I help you? ( 3s ) Customer: Thank you( 40s ) Customer: I have a question about X. ( 8m 1s ) Agent: I can help here. Log in this website (remember to use your new password) ( 11m 31s )"

def cleanup(text):
    for word in ('Agent','Customer'):
        text = text.replace(word,f'\n{word}').strip()
    clean_text = [line[:line.rindex('(')] for line in text.splitlines()]

    # or in slow-motion
    # clean_text = []
    # for line in text.splitlines():
    #     idx = line.rindex('(')
    #     line = line[:idx]
    #     clean_text.append(line)

    return ' '.join(clean_text)

print(cleanup(spam))

输出

Agent: Can I help you?  Customer: Thank you Customer: I have a question about X.  Agent: I can help here. Log in this website (remember to use your new password)

编辑:正如 @DRPK 所建议的,它可以通过使它成为一个在大语料库中产生差异的衬垫来优化

clean_text = ' '.join([line[:line.rindex('(')] for line in text.replace("Agent",'\nAgent').replace("Customer",'\nCustomer').strip().splitlines()])
,
\( [^\)]++\)

您可以使用此正则表达式替换代码中的“”。 我确实从 http://www.amazingregex.xyz/ 生成它。可以自己生成文本示例