我正在努力从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