【问题标题】:Substituting alphanumeric substrings with single unicode from a table用表中的单个 unicode 替换字母数字子串
【发布时间】:2017-06-27 02:37:37
【问题描述】:

给定输入:

nguye64n tra62n huye62n my

期望的输出:

nguyễn trần huyền my

我一直在使用替代表并迭代每个字符以查找数字,缓存它们并在其后跟非数字字符时转换它们:

substitute = {'e64': u'ễ', 'a62': u'ầ', 'e62': 'ề'}
s = 'nguye64n tra62n huye62n my'
tonal = ''
x = ''
for ch in s:
    if ch.isdigit():
        tonal += ch
    else:
        if tonal:
            tonal = substitute[x[-1] + tonal]
            x = x[:-1] + tonal
            tonal = ''
        x += ch

[出]:

>>> x
'nguyễn trần huyền my'

在给定替换表的情况下,是否有更简单的方法来实现相同的输出?也许是正则表达式替换或一些 str.translate 操作?

【问题讨论】:

    标签: python regex string unicode substitution


    【解决方案1】:

    函数re.sub可用于根据函数替换匹配项。这里我使用了一个 lambda 函数来处理匹配并从查找表中替换它:

    #coding:utf8
    import re
    
    substitute = {'e64': u'ễ', 'a62': u'ầ', 'e62': 'ề'}
    s = 'nguye64n tra62n huye62n my'
    x = re.sub(r'[a-z]\d+',lambda m: substitute[m.group(0)],s)
    print(x)
    

    nguyễn trần huyền my

    【讨论】:

    • 如果您使用substitute.get(m.group[0], m.group[0]) 而不是substitute[m.group(0)],当字典中没有匹配项时,您将不会得到KeyError,它将返回原始文本。这可能是也可能不是想要的行为
    猜你喜欢
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 2021-12-10
    • 2020-06-16
    • 2021-04-09
    • 2023-03-23
    • 2021-05-01
    • 1970-01-01
    相关资源
    最近更新 更多