单次传递多次重新查找并替换ignorecase

时间:2018-03-13 04:28:19

标签: python

我想执行单次传递多次查找和替换但忽略大小写。我接触到下面的内容,在接受区分大小写时非常有效。有谁知道如何利用下面忽略这种情况的方法?

import re 

def multiple_replace(dict, text):
    regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
    return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text) 

if __name__ == "__main__": 

    text = "Test one, test One, test Two, tEst three"

    dict = {
      "Test one" : "Test 1",
      "Test Two" : "Test 2",
      "Test three" : "Test 3",
    } 

print multiple_replace(dict, text)

例如:在上面我想看到所有的键都被映射到忽略键情况的值。

如果有人能指出我正确的方向,我们将不胜感激

1 个答案:

答案 0 :(得分:1)

您可以使用以下功能:

def multiple_replace(my_dict, text):
    # first create a new dict by converting key values to lower case
    # this will help with the lookup later
    my_dict_lower = {k.lower(): v for k, v in my_dict.items()}

    # add re.IGNORECASE flag for case insenstivity
    regex = re.compile("(%s)" % "|".join(map(re.escape, my_dict_lower.keys())), re.IGNORECASE)

    # you can directly use mo.group() to get the matched text.
    # convert it to lower case and get the value from dict to replace with.
    return regex.sub(lambda mo: my_dict_lower[mo.group(0).lower()], text)

通过上面的例子:

>>> text = "Test one, test One, test Two, tEst three"
>>> my_dict = {
...     "Test one": "Test 1",
...     "Test Two": "Test 2",
...     "Test three": "Test 3",
... }
>>> multiple_replace(my_dict, text)
'Test 1, Test 1, Test 2, Test 3'