【问题标题】:Append unicode code points with their corresponding glyphs in a string在字符串中附加 unicode 代码点及其对应的字形
【发布时间】:2017-02-26 02:00:37
【问题描述】:

我在 python 中有一个字符串

set = "U+06A4, U+06A7, U+06A8, U+06A9, U+06AF"

我想在这个字符串中找到所有以U+ 开头的单词,并将它们附加到相应的字形中。

比如说

word_found_in_string = 'U+064A'

我想换成

replace_with = 'U+064A chr(int(word_found_in_string[2:6],16))'

chr(int(word_found_in_string[2:6],16)) 在我的输出文件中打印相应的字形。

如何使用re 模块对字符串中的所有 unicode 代码点执行此操作,以便生成的字符串中的所有代码点都附加了相应的字形?

【问题讨论】:

    标签: regex python-3.x unicode


    【解决方案1】:

    re.sub 可以带一个函数进行替换。这里我使用了一个 lambda 函数。对于正则表达式的每个匹配,它都与匹配对象一起调用。 m.group(0) 是整个匹配项,m.group(1) 是匹配四个十六进制数字的括号表达式。

    import re
    s = 'U+06A4, U+06A7, U+06A8, U+06A9, U+06AF'
    s = re.sub(r'U\+([0-9A-F]{4})',lambda m: m.group(0)+' '+chr(int(m.group(1),16)),s)
    print(s)
    

    输出:

    U+06A4 ڤ, U+06A7 ڧ, U+06A8 ڨ, U+06A9 ک, U+06AF گ
    

    【讨论】:

    • 谢谢马克。这正是我想要的。
    猜你喜欢
    • 2020-01-21
    • 2021-11-08
    • 2011-10-22
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 2010-11-02
    • 2013-02-09
    • 1970-01-01
    相关资源
    最近更新 更多