python emoji filter

http://my.oschina.net/jiemachina/blog/189460

Note that the replaced emoji are standard emoji characters. Each emoji is originally 2 bytes. After replacing it with a string, each emoji becomes 12 characters, which wastes a lot of space, but it is simple and does not need to be specially written. map one-to-one correspondence;

turn emojis into strings

def filter_emoji(desstr,restr=''):
'''
过滤表情
'''
try:
co = re.compile(u'[\U00010000-\U0010ffff]')
except re.error:
co = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')
return co.sub(restr, desstr)

 

turn string into emoji

def str_2_emoji(emoji_str):
'''
Convert the string to emoji
'''
if not emoji_str:
return emoji_str
h = HTMLParser.HTMLParser()
emoji_str = h.unescape(h.unescape(emoji_str)) #match
u"\U0001f61c "And u"\u274c" the expression string
co = re.compile(ur"u[\'\"]\\[Uu]([\w\"]{9}|[\w\"] {5})")
pos_list=[]
result=emoji_str #Find the
location first
for m in co.finditer(emoji_str):
pos_list.append((m.start(),m.end())) #Splice and
replace according to the location
for pos in range(len(pos_list)):
if pos==0:
result=emoji_str[0:pos_list[0][0]]
else:
result=result+emoji_str[pos_list[pos-1][1]:pos_list[pos][0]]
result = result +eval(emoji_str[pos_list[pos][0]:pos_list[pos][1]])
if pos==len(pos_list)-1:
result=result+emoji_str[pos_list[pos][1]:len(emoji_str)]
return result

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324610940&siteId=291194637