2010-11-21 96 views
0

我有一個字符串。 。Python:替換標籤但保留內部文本?

"This is an [[example]] sentence. It is [[awesome]]

我想<b>.</b>更換的[[.]]所有實例保留通過.

匹配通配符文本的結果應該是: "This is an <b>example</b> sentence. It is <b>awesome</b>」。

我可以去和手動<b>]]</b>取代[[,但它更有意義,只是做了一次,並保留標籤之間的文本。

我該怎麼做?

注意:這是爲了從數據庫中獲取源代碼並將其轉換爲HTML。它應該模仿wiki風格的語法。在這種情況下,[[x]]會以粗體字顯示。

回答

5

你可以使用弦上replace方法。

>>> s = 'This is an [[example]] sentence. It is [[awesome]].' 
>>> s.replace('[[', '<b>').replace(']]', '</b>') 

'This is an <b>example</b> sentence. It is <b>awesome</b>.' 

只是爲了得到一些timeit結果在這裏:

$ python -mtimeit -s'import re' "re.sub(r'\[\[(.*?)\]\]', r'<b>\1</b>', 'This is an [[example]] sentence. It is [[awesome]]')"'' 
100000 loops, best of 3: 19.7 usec per loop 

$ python -mtimeit '"This is an [[example]] sentence. It is [[awesome]]".replace("[[", "<b>").replace("]]", "</b>")' 
100000 loops, best of 3: 1.94 usec per loop 

如果我們編譯的正則表達式,我們得到表現稍好:

$ python -mtimeit -s"import re; r = re.compile(r'\[\[(.*?)\]\]')" "r.sub(r'<b>\1</b>', 'This is an [[example]] sentence. It is [[awesome]]')" 
100000 loops, best of 3: 16.9 usec per loop 
2

該代碼允許您隨意擴展替換列表。

import re 

_replacements = { 
    '[[': '<b>', 
    ']]': '</b>', 
    '{{': '<i>', 
    '}}': '</i>', 
} 

def _do_replace(match): 
    return _replacements.get(match.group(0)) 

def replace_tags(text, _re=re.compile('|'.join(re.escape(r) for r in _replacements))): 
    return _re.sub(_do_replace, text) 

print replace_tags("This is an [[example]] sentence. It is [[{{awesome}}]].") 

This is an <b>example</b> sentence. It is <b><i>awesome</i></b>. 
3

如何使用re.sub()和一點點正則表達式魔術:

import re 
re.sub(r'\[\[(.*?)\]\]', r'<b>\1</b>', "This is an [[example]] sentence. It is [[awesome]]"); 
+3

\ 1」應該是R「\ 1‘或’\\ 1」,讓反斜線被正確地傳遞給正則表達式引擎,而不是轉換爲ASCII 001一旦這樣改變了它的工作原理大。 – cecilkorik 2010-11-21 03:29:23

+0

'@ aaronasterling'和'@ cecilkorik'謝謝你們,我把它遺漏了,當我看到我的錯誤時立即編輯了我的答案。 :) – Alex 2010-11-21 03:30:47

0

的方法由其他海報肯定會建議工作,但是我想指出的是,使用正則表達式來完成這個任務會帶來相當大的性能影響。

您提供的示例也可以使用本地Python字符串操作來解決,並且執行速度將快大約3倍。

例如:

>>> import timeit 
>>> st = 's = "This is an [[example]] sentence. It is [[awesome]]"' 
>>> t = timeit.Timer('s.replace("[[","<b>").replace("]]","</b>")',st) 
>>> t.timeit() # Run 1000000 times 
1.1733845739904609 
>>> tr = timeit.Timer("re.sub(r'\[\[(.*?)\]\]', r'<b>\1</b>',s)",'import re; ' + st) 
>>> tr.timeit() # Run 1000000 times 
3.7482673050677704 
>>> 

希望這有助於:)

+0

@Reznor這是否回答你的問題? – nonot1 2010-11-22 04:35:12

1

...使用正則表達式的方法在這裏可能是,它可以防止在做替換時,源文本沒有的優勢有匹配的配對[[]]

也許很重要,也許不是。