gpt4 book ai didi

python - 用其描述或名称替换表情符号

转载 作者:太空宇宙 更新时间:2023-11-03 14:16:12 41 4
gpt4 key购买 nike

我正在努力从 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 - 用其描述或名称替换表情符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32987536/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com