如何在Python中使用REGEX在两种不同的条件下用两个不同的<remarks>替换相同的符号

2024-09-27 07:25:38 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我试着做一个正则表达式来替换守时和其他符号,如果标点重复,例如“!!!”=>;“!”)

对于输入:

....    
??  
>>>>>
^   
%

如果我应用以下正则表达式,那么:

text = re.sub(r'([@+*&%$#\\|_=`~>.,?!"</)({}-]){2,}', r'\1 <REPEAT>', text) # Mark punctuation repetitions (eg. "!!!" => "! <REPEAT>")
text = re.sub(r'([@+*&%$#;:\^\]\[\\|_=`~>.,?!"</)({}-])', r'\1 <PUNC>', text) # Mark punctuation as <PUNC> 

我得到的结果如下:

['. <punc> < <punc>repeat> <punc>', '! <punc> < <punc>repeat> <punc>', '? <punc> < <punc>repeat> <punc>', '> <punc> < <punc>repeat> <punc>', '^ <punc>', '% <punc>']

应该是:

['. <repeat> ', '! <repeat> ', '? <repeat> ', '> <repeat>', '^ <punc>', '% <punc>']

谁能告诉我解决办法吗? 提前谢谢


Tags: textgtreas符号markrepeateg
1条回答
网友
1楼 · 发布于 2024-09-27 07:25:38

我建议避免对字符串进行两次处理:使用一个带有两个替代项的正则表达式,并在lambda表达式中处理匹配项:

import re
texts = ["....", "!!!!", "??", ">>>>>", "^", "%"]
rx_repeat = r'([@+*&%$#\\|_=`~>.,?!"</(){}-]){2,}'
rx_punc = r'[@+*&%$#;:\^\]\[\\|_=`~>.,?!"</(){}-]'
pat = r'{}|{}'.format(rx_repeat, rx_punc)
texts = [re.sub(pat, lambda x: r'{} <REPEAT>'.format(x.group(1)) if x.group(1) else r'{} <PUNC>'.format(x.group()), text) for text in texts]
print(texts)
# => ['. <REPEAT>', '! <REPEAT>', '? <REPEAT>', '> <REPEAT>', '^ <PUNC>', '% <PUNC>']

参见Python demo

相关问题 更多 >

    热门问题