2017-04-07 15 views
0

こんにちは私はPunctualtionsと他のシンボルを置き換える正規表現を作成しようとしていました。例えば。 "!!!" =>)PythonのREGEXを使用して2つの異なる条件で同じシンボルを2つの異なる条件で置き換える方法

入力のための "!":

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

私は、正規表現の下に適用された場合:

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

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> 

私はのような出力を取得しています

ここにあるはずです:

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

解決策を教えていただけますか? ありがとうございます。

+0

を参照してください ' <> '最初の正規表現で ' 'を代用すると、2番目の正規表現は' < repeat 'になります。解決策:これらの '<>'を2番目のregex_から出す?または、あなたはちょうどlookbehind '(?<= [@ + * &%$#;:\^\] \ [\\ | _ = \'〜。、?! "」に置き換えてください – sln

答えて

0

私は二回、文字列を処理するために避けることをお勧め:2つの選択肢を持つ単一の正規表現を使用し、ラムダ式の内部一致を処理:

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

関連する問題