【问题标题】:find all the matches for unicodes in a string in python在python中的字符串中查找unicode的所有匹配项
【发布时间】:2017-04-15 14:53:04
【问题描述】:
import re

b="united thats weak. See ya ????"
print b.decode('utf-8')  #output: u'united thats weak. See ya \U0001f44b'

print re.findall(r'[\U0001f600-\U0001f650]',b.decode('utf-8'),flags=re.U) # output: [u'S']

如何获得输出\U0001f44b。请帮忙

我需要处理的表情符号是“??????❤️?????????????????????????????????????????????? ???????????????????????????? ?????????????????????????????????????????????????????????????????? ???????????????????????????? ?????????????????????????????????????????????????????????????????? ???????????????????????????? ?????????????????????????????????????????????????????????????????? ???????????????????????????? ?????????????????????????????????????????????????????????????????? ???????????????????????????? ?????????????????????????????????????????????????????????????????? ?????? ??????????????????????????? ??????????????????????????????????????????????????????????????? ??????????????????????????? ??????????????????????????????????????????????????????????????? ??????????????????????????? ??????????????????????????????????????????????????????????????? ??????????????????????????? ???????????”

【问题讨论】:

  • 这是否意味着您只需要匹配一些表情符号?
  • 是的...我正在尝试这样做...但不知何故无法写出准确的模式
  • 你能用所有你想匹配的表情来更新你的问题吗?谢谢。
  • 嗨 Qubad....我只需要一种使用正则表达式来处理表情符号的方法...它不是关于特定表情符号的更多信息。感谢您的回复:)

标签: python regex python-2.7 unicode python-unicode


【解决方案1】:

搜索 unicode 范围与搜索任何类型的字符范围完全相同。但是,您需要正确表示字符串。这是一个工作示例:

#coding: utf-8
import re

b=u"united thats weak. See ya ? "
assert re.findall(u'[\U0001f600-\U0001f650]',b) == [u'?']
assert re.findall(ur'[?-?]',b) == [u'?']

注意事项:

  • 您的程序的第一行或第二行需要#coding: utf-8 或类似名称。
  • 在您的示例中,您使用的表情符号 U-1f44b 不在 U-1f600 到 U-1f650 的范围内。在我的示例中,我使用了一个。
  • 如果您想使用 \U 包含 unicode 字符,则不能使用原始字符串前缀 (r'')。
  • 但如果您使用字符本身(而不是\U 转义),则可以使用原始字符串前缀。
  • 您需要确保模式和输入字符串都是 unicode 字符串。它们都不能是 UTF8 编码的字符串。
  • 但您不需要re.U 标志,除非您的模式包括\s\w 或类似的。

【讨论】:

    猜你喜欢
    • 2023-01-06
    • 2017-11-14
    • 1970-01-01
    • 2013-03-19
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多