【发布时间】: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