【问题标题】:Substitution substrings from a key-value table替换键值表中的子字符串
【发布时间】:2017-07-03 08:14:40
【问题描述】:

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

>>> 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' 之前。理想情况下,应首先更换较长的密钥。

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

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

【问题讨论】:

    标签: python regex string substring substitution


    【解决方案1】:

    按长度降序对telex_mappings 键进行排序:

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

    【讨论】:

    • 你可以放弃.keys()
    【解决方案2】:

    这是一个可能的正则表达式解决方案:

    import re
    
    pattern= '|'.join(re.escape(word) for word in sorted(telex_mappings, key=len, reverse=True))
    result= re.sub(pattern, lambda match:telex_mappings[match.group()], s)
    

    这会按长度对字典键进行排序,然后创建key1|key2|key3|... 形式的正则表达式模式,最后用相应的字典值替换该模式的所有出现。

    【讨论】:

    • lambda match: telex_mappings[match.group(0)] 会一样吗?
    • 感谢@Rawing!然后我猜telex_mapping.get(m.group(0), m.group(0)) 最好避免 KeyError =)
    • 我看不出这怎么会产生 KeyError。毕竟,正则表达式模式是从 dict 键创建的。
    • 啊,是的,它不同于检索单独的手写正则表达式!再次感谢!!
    猜你喜欢
    • 1970-01-01
    • 2017-06-22
    • 2011-01-07
    • 2022-08-14
    • 2022-01-15
    • 1970-01-01
    • 2021-01-02
    • 2012-04-03
    • 2013-07-23
    相关资源
    最近更新 更多