python特殊字符解码/编码

2024-09-30 20:38:44 发布

您现在位置:Python中文网/ 问答频道 /正文

如何翻译以下字符串

H.P. Dembinski, B. K\'{e}gl, I.C. Mari\c{s}, M. Roth, D. Veberi\v{c}

进入

^{pr2}$

是吗?在


Tags: 字符串glpr2marirothdembinskiveberi
2条回答
>>> s = "H.P. Dembinski, B. K\\'{e}gl, I.C. Mari\\c{s}, M. Roth, D. Veberi\\v{c}"
>>> s.replace(u"\\'{e}", u"\xe9").replace(u"\\c{s}", u"\u015f").replace(u"\\v{c}", u"\u010d")
u'H.P. Dembinski, B. K\xe9gl, I.C. Mari\u015f, M. Roth, D. Veberi\u010d'

这当然是暴力手段。正如您所说,您将有许多可能的替代品,这里有另一种方法,仍然是蛮力,但更干净:

^{pr2}$

由于替换字符串有一个通用模式,因此您也可以利用正则表达式。在

>>> import re
>>> split = re.split(u"(\\\\['a-z]{[a-z]})", s)
>>> table = {u"\\'{e}": u"\xe9", u"\\c{s}": u"\u015f", u"\\v{c}": u"\u010d"}
>>> ''.join(table[piece] if piece in table else piece for piece in split)
u'H.P. Dembinski, B. K\xe9gl, I.C. Mari\u015f, M. Roth, D. Veberi\u010d'

这段代码应该处理示例中的模式。现在添加rest of those codes就足够了。把它们放到桌子上就行了。在

#!/usr/bin/python3
import re, unicodedata, sys

table = {
        'v': '\u030C',
        'c': '\u0327',
        "'": '\u0301'
        # etc...
        }

def despecial(s):
    return re.sub(r"\\(" + '|'.join(map(re.escape, table)) + r")\{(\w+)}",
            lambda m: m.group(2) + table[m.group(1)],
            s)

if __name__ == '__main__':
    print(unicodedata.normalize('NFC', despecial(' '.join(sys.argv[1:]))))

示例:

^{pr2}$

示例(命令行):

$ ./path/to/script.py "Hello W\v{o}rld"
Hello Wǒrld

它将适当的Unicode组合字符放在给定参数之后。具体地说:U+0301组合锐音符,U+0327组合塞迪拉,U+030C组合抑扬符。如果你想合成字符串,你可以用^{}或其他东西来规范化它。在

>>> import unicodedata
>>> unicodedata.normalize('NFC', despecial(r"H.P. Dembinski, B. K\'{e}gl, I.C. Mari\c{s}, M. Roth, D. Veberi\v{c}"))
'H.P. Dembinski, B. Kégl, I.C. Mariş, M. Roth, D. Veberič'

也就是说,我相信有更好的方法来处理这件事。看起来你有乳胶密码。在

相关问题 更多 >