2012-08-10 27 views
-1
l = ':;\'"[email protected]#$%^&*()_-=+][{}~`.><?/\\|' # list of character that can be used for emoticons 

s = '<p>This :) is an example for:) emoticons :)</p>' 

我用s.replace(':)', '<img>')和人物,Python的 - 更換的表情

result = '<p>this <img> is an example for<img> emoticons <img></p>' 

如何使結果類似:

result = '<p>this <img> is an example for:) emoticons <img></p>' 

感謝您的幫助!

編輯:我有一個初始名單l。用戶只能使用l中的字符製作表情符號。例如::),:],等。對於每個表情符號,我將分別將其更改爲圖像作爲迴應。因此用戶必須正確輸入數據:通配符應該是獨立的。最難的部分是輸入數據包含HTML標籤。

+3

更具體一些。當「」子字符串被空白包圍時,是否只想進行替換?你想「爲:)」變成「爲」? – 2012-08-10 22:05:18

+0

我不知道太多的python,但我認爲你可以這樣做:1)首先搜索第二''並返回這個索引2)你可以分成兩部分s [1-index] s [( index + 4)-length(s)] 3)現在你可以使用replace()。 – 2012-08-10 22:07:42

+0

哦,我的壞。編輯! :) – ben 2012-08-10 22:07:51

回答

2
import re 
emos = { ':)' : 'smiley.jpg', 
     ':(' : 'saddy.jpg', 
     ';p' : 'bllinky.jpg' } 
pattern = re.compile('|'.join(re.escape(emo) for emo in emos)) 
def emoImg(emoMatch): 
    return '<img src = "/images/{0}>'.format(emos[emoMatch.group(0)]) 
def emoSub(string): 
    return pattern.sub(emoImg,string) 
print(emoSub('Hi :) I miss you :(')) 
1
>>> s = '<p>This :) is an example for:) emoticons :)</p>' 
>>> s.replace(' :)', ' <img>') 
'<p>This <img> is an example for:) emoticons <img></p>' 

如果你只想做替換,該模式是具有領先的空間,把領先的空間周圍的匹配和替代兩者。

+0

Brenden和我用我們的答案完成了同樣的事情:他的':)'等同於我的'\ s:\\''(\ s是一個空格,並且:\\)是:)與)轉義) 。支持他這樣做,而不是拖拽正則表達式;然而,如果你的用例比這更復雜,你實際上可能不得不開始使用正則表達式。 – verbsintransit 2012-08-10 22:25:52

+0

非常真實。我剛剛解決了這個小事。任何更復雜的東西,正則表達式就是它的位置。 – 2012-08-10 22:28:43

1
import re 
s = '<p>This :) is an example for:) emoticons :)</p>' 
s = re.sub('\s:\)', ' <img>',s)