2014-01-21 100 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)