嗨,我试着做一个正则表达式来替换守时和其他符号,如果标点重复,例如“!!!”=>;“!”)
对于输入:
....
??
>>>>>
^
%
如果我应用以下正则表达式,那么:
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>']
谁能告诉我解决办法吗? 提前谢谢
我建议避免对字符串进行两次处理:使用一个带有两个替代项的正则表达式,并在lambda表达式中处理匹配项:
参见Python demo
相关问题 更多 >
编程相关推荐