2014-01-21 99 views
1

我新的模式匹配和具有作爲這樣的:字模式匹配和編譯

def replaceSynonymns(title, words): 
    pattern = re.compile(r'\b(' + '|'.join(words) + ')\b') 
    title = re.sub(pattern, words[0], title) 
    return title 

這樣的一個例子,是[「網」,「互聯網」,「在線」,「數字'],因此如果我們把標題設置爲'我在互聯網上',我們應該得到'我在網上'

但不幸的是它不工作 - 因爲我不認爲公司進入編譯模式部分的列表是正確的 - 任何提示?

回答

2

使用原始字符串最後一個字符串,以及:

>>> r'\b(' + '|'.join(words) + ')\b' 
'\\b(web|internet|online|digital)\x08' 
           ^
           not escaped 

或者更好地利用string formatting

>>> r'\b({})\b'.format('|'.join(words)) 
'\\b(web|internet|online|digital)\\b' 

由於

>>> r'\b(' + '|'.join(words) + r')\b' 
'\\b(web|internet|online|digital)\\b' 

否則,你就結了一個附註,你可以在編譯模式本身上使用.sub

title = pattern.sub(words[0], title)