2010-04-15 30 views
6

我想搜索關鍵詞(鍵將是動態的)並以特定格式替換它們。例如: 這些數據如何用正則表達式替換爲python中的小寫

keys = ["cat", "dog", "mouse"] 
text = "Cat dog cat cloud miracle DOG MouSE" 

必須轉換爲

converted_text = "[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](dog) [MouSE](mouse)" 

這裏是我的代碼:

keys = "cat|dog|mouse" 
p = re.compile(u'\\b(?iu)(?P<name>(%s))\\b' % keys) 
converted_text = re.sub(p, '[\g<name>](\g<name>)', text) 

而且這工作得很好,只是我不能最後一個參數轉換以小寫字母表示。這種轉換是這樣的:

converted_text = "[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](DOG) [MouSE](MouSE)" 

我怎樣才能將最後一個參數轉換爲小寫?看來python無法編譯\ L標誌。

+0

沒有必要爲不傳遞更多信息,任何額外的標記,zomboid – SilentGhost 2010-04-15 10:35:38

+0

*正則表達式*是Stack Overflow上正則表達式的標籤。 – Gumbo 2010-04-15 10:36:11

回答

10

您可以使用一個函數來做到的更換:

pattern = re.compile('|'.join(map(re.escape, keys)), re.IGNORECASE) 
def format_term(term): 
    return '[%s](%s)' % (term, term.lower()) 

converted_text = pattern.sub(lambda m: format_term(m.group(0)), text) 
3

沒有必要使用正則表達式

>>> keys = ["cat", "dog", "mouse"] 
>>> text = "Cat dog cat cloud miracle DOG MouSE" 
>>> for w in text.split(): 
...  if w.lower() in keys: 
...  print "[%s]%s" %(w,w.lower()), 
...  else: 
...  print w, 
... 
[Cat]cat [dog]dog [cat]cat cloud miracle [DOG]dog [MouSE]mouse 
1

從你提出的解決方案,我想我並不需要保持鍵作爲一個列表(我將使用一組,以加快搜索速度)。這個答案也假定文本中的所有單詞都被一個空格分隔(我將用它來加入它們)。給這些,你可以使用:

>>> keys = (["cat", "dog", "mouse"]) 
>>> text = "Cat dog cat cloud miracle DOG MouSE" 
>>> converted = " ".join(("[%s](%s)" % (word, word.lower()) if word.lower() in keys else word) for word in text.split()) 
>>> converted 
'[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](dog) [MouSE](mouse)' 

當然,這會調用word.lower()兩次。您可以使用兩個列表內涵避免這種情況(和仍然使用類似的方法)(或者,實際上,發電機表達式):

>>> converted = " ".join(("[%s](%s)" % (word, lower) if lower in keys else word) for word, lower in ((w, w.lower()) for w in text.split())) 
>>> converted 
'[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](dog) [MouSE](mouse)'