[英]Python - Replace characters for emoticons
l = ':;\'"!@#$%^&*()_-=+][{}~`.><?/\\|' # list of character that can be used for emoticons
s = '<p>This :) is an example for:) emoticons :)</p>'
I used s.replace(':)', '<img>')
and, 我使用了
s.replace(':)', '<img>')
和
result = '<p>this <img> is an example for<img> emoticons <img></p>'
How to make the result like: 如何使结果像:
result = '<p>this <img> is an example for:) emoticons <img></p>'
Thanks for any help! 谢谢你的帮助!
EDIT: I have a initial list l
. 编辑:我有一个初始列表
l
。 Users can only make a emoticon from characters in l
. 用户只能从
l
字符制作图释。 For example: :)
, :]
, ect. 例如:
:)
,: :]
等。 With each emoticon, I will change it to an image respectively in response. 对于每个表情符号,我将分别将其更改为图像。 So users must enter data correctly: the wildcard should stand alone.
因此,用户必须正确输入数据:通配符应独立存在。 The hard part is the input data include HTML tags.
困难的部分是输入数据包括HTML标记。
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 :('))
>>> s = '<p>This :) is an example for:) emoticons :)</p>'
>>> s.replace(' :)', ' <img>')
'<p>This <img> is an example for:) emoticons <img></p>'
If you only want to make replacements where the pattern is has a leading space, put a leading space around both the match and the substitution. 如果只想在模式有前导空格的地方进行替换,请在匹配项和替换项之间都放置一个前导空格。
import re
s = '<p>This :) is an example for:) emoticons :)</p>'
s = re.sub('\s:\)', ' <img>',s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.