2017-04-07 54 views
0

嗨我試圖用一個正則表達式來替換標點符號和其他符號,如果標點符號重複,例如,例如。 「!!!」 =>)如何用Python中的REGEX在兩種不同的條件下用兩種不同的<remarks>代替相同的符號

用於輸入 「!」:

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

如果我申請了下面的正則表達式,則:

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>'] 

任何人都可以讓我知道解決方案嗎? 在此先感謝。

+0

同時包括在正則表達式是這些符號' <>'。在第一個正則表達式中替換「」後,第二個將其替換爲「< 」重複'。解決方案:將這些'<>'從第二個正則表達式中取出?或者,你可以使用後視圖(<?[= + @ &%$#;:\^\] \ [\\ | _ = \'〜>,?!「' – sln

回答

0

我建議避免處理該字符串兩次:使用單一的正則表達式與2層的替代品和處理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

相關問題