Skip to main content
 首页 » 编程设计

python之替换键值表中的子字符串

2025年05月04日23lonelyxmas

给定一个多字符到单字符的字符串转换表:

>>> telex_mappings 
{'eer': 'ể', 'awj': 'ặ', 'Dd': 'Đ', 'Ooj': 'Ộ', 'oox': 'ỗ', 'Aas': 'Ấ', 'Eej': 'Ệ', 'awx': 'ẵ', 'eef': 'ề', 'oo': 'ô', 'aas': 'ấ', 'Aax': 'Ẫ', 'owr': 'ở', 'Uws': 'Ớ', 'Awj': 'Ặ', 'Oor': 'Ổ', 'Awf': 'Ằ', 'ows': 'ớ', 'aaj': 'ậ', 'Owj': 'Ợ', 'aa': 'â', 'eex': 'ễ', 'Oox': 'Ỗ', 'Owr': 'Ở', 'awf': 'ằ', 'Aa': 'Â', 'aw': 'ă', 'awr': 'ẳ', 'uwj': 'ợ', 'uwx': 'ỡ', 'owj': 'ợ', 'Awx': 'Ẵ', 'Uwr': 'Ở', 'Aaj': 'Ậ', 'Eex': 'Ễ', 'Awr': 'Ẳ', 'Uw': 'Ư', 'Eef': 'Ề', 'aaf': 'ầ', 'Aws': 'Ắ', 'ees': 'ế', 'Ee': 'Ê', 'Ow': 'Ơ', 'Ees': 'Ế', 'Owx': 'Ỡ', 'Eer': 'Ể', 'Aar': 'Ẩ', 'Oo': 'Ô', 'uwf': 'ờ', 'uw': 'ư', 'uws': 'ớ', 'owx': 'ỡ', 'ow': 'ơ', 'aar': 'ẩ', 'eej': 'ệ', 'oof': 'ờ', 'ee': 'ê', 'uwr': 'ở', 'Aw': 'Ă', 'ooj': 'ộ', 'Aaf': 'Ầ', 'aax': 'ẫ', 'Oof': 'Ờ', 'oor': 'ổ', 'aws': 'ắ', 'Oos': 'Ớ', 'Uwf': 'Ờ', 'Uwx': 'Ỡ', 'dd': 'đ', 'oos': 'ố', 'Uwj': 'Ợ'} 
 
>>> telex_mappings['eef'] 
'ề' 
>>> telex_mappings['aaf'] 
'ầ' 
>>> telex_mappings['uw'] 
'ư' 

和输入字符串:

>>> s = 'Nguyeefn Traafn Anh Thuw' 

所需的功能类似于:

>>> func('Nguyeefn Traafn Anh Thuw') 
'Nguyên Trân Anh Thư' 

我试过:

>>> s = 'Nguyeefn Traafn Anh Thuw' 
>>> for k,v in telex_mappings.items(): 
...     s = s.replace(k, v) 
...  
>>> s 
'Nguyền Trâfn Anh Thư' 

但是我们看到 'aa' 有一个键,它导致替换先于 'aaf' 发生。理想情况下,应先更换较长的 key 。

应该如何替换才能从最长的键开始替换键值表中的子字符串?

是否有某种正则表达式方法而不是遍历映射中的所有键值对?

请您参考如下方法:

按长度降序排列 telex_mappings 键:

for k in sorted(telex_mappings, key=len, reverse=True): 
    s = s.replace(k, telex_mappings[k])