我有一個正則表和替換函數的列表。正則表達式與Unicode和str
regex function
replacement_patterns = [(ur'\\u20ac', ur' euros'),(ur'\xe2\x82\xac', r' euros'),(ur'\b[eE]?[uU]?[rR]\b', r' euros'), (ur'\b([0-9]+)[eE][uU]?[rR]?[oO]?[sS]?\b',ur' \1 euros')]
class RegexpReplacer(object):
def __init__(self, patterns=replacement_patterns):
self.patterns = [(re.compile(regex, re.UNICODE | re.IGNORECASE), repl) for (regex, repl) in patterns]
def replace(self, text):
s = text
for (pattern, repl) in self.patterns:
(s, count) = re.subn(pattern, repl, s)
return s
如果我寫的字符串作爲波紋管:
string='730\u20ac.\r\n\n ropa surf ... 5,10 muy buen estado..... 170 \u20ac\r\n\nPack 850\u20ac, reparaci\u00f3n. \r\n\n'
replacer = RegexpReplacer()
texto= replacer.replace(string)
我得到完美的結果。
但是,如果我遍歷一個JSON文件時我剛裝調用的函數,它不工作(沒有錯誤,但沒有替換)
有什麼事發生的是,當我調用該函數在類型化該函數接收一個STR,當我從JSON迭代中調用它時,它會收到一個unicode。
我的問題是爲什麼我的正則表達式不在unicode上工作,它不應該是?
我的猜測是JSON包含的東西比你想象的要多。也許'\\ u20ac'(字面反斜槓,字母u,數字2,0,字母a,c)而不是文字'\ u20ac'? – tripleee
'你'\\ u20ac''這是錯的。你想要'你'\ u20ac''。你的unicode字符串中也不應該有utf-8編碼的數據。 – beerbajay
@beerbajay很多謝謝!我想我現在知道了......如果我用你的'',我不需要第一個\告訴正則表達式它是一個普通的字符?但如果我用r'',我不需要? – user2950162