python表情换头_python – 用其描述或名称替换表情符号

我正在努力从API检索的文本中获取表情符号的子集.我想做的是用每个表情符号替换它的描述或名称.

我正在使用Python 3.4,我目前的方法是使用unicodedata访问unicode的名称,如下所示:

nname = unicodedata.name(my_unicode)

我用re.sub代替:

re.sub('[\U0001F602-\U0001F64F]', 'new string', str(orig_string))

我已经尝试了re.search,然后访问匹配和替换字符串(不使用正则表达式)但无法解决这个问题.

有没有办法获得re.sub所做的每个替换的回调?任何其他路线也不胜感激.

解决方法:

您可以将回调函数传递给re.sub:从文档中:

re.sub(pattern, repl, string, count=0, flags=0)

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; […] If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.

所以只需使用unicodedata.name作为回调:

>>> my_text ="\U0001F602 and all of this \U0001F605"

>>> re.sub('[\U0001F602-\U0001F64F]', lambda m: unicodedata.name(m.group()), my_text)

'FACE WITH TEARS OF JOY and all of this SMILING FACE WITH OPEN MOUTH AND COLD SWEAT'

标签:python,python-3-x,unicode,regex

来源: https://codeday.me/bug/20190829/1762817.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值