代码之家  ›  专栏  ›  技术社区  ›  jargalan

在Python中如何用正则表达式替换为小写

  •  6
  • jargalan  · 技术社区  · 15 年前

    我想搜索关键字(关键字是动态的)并以某种格式替换它们。例如: 这些数据

    keys = ["cat", "dog", "mouse"]
    text = "Cat dog cat cloud miracle DOG MouSE"
    

    必须转换为

    converted_text = "[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](dog) [MouSE](mouse)"
    

    这是我的代码:

    keys = "cat|dog|mouse"
    p = re.compile(u'\\b(?iu)(?P<name>(%s))\\b' % keys)
    converted_text = re.sub(p, '[\g<name>](\g<name>)', text)
    

    这很好,只有我不能把最后一个参数转换成小写。这样转换:

    converted_text = "[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](DOG) [MouSE](MouSE)"
    

    如何将最后一个参数转换为小写?似乎python无法编译\l符号。

    3 回复  |  直到 15 年前
        1
  •  10
  •   Ants Aasma    15 年前

    您可以使用函数进行替换:

    pattern = re.compile('|'.join(map(re.escape, keys)), re.IGNORECASE)
    def format_term(term):
        return '[%s](%s)' % (term, term.lower())
    
    converted_text = pattern.sub(lambda m: format_term(m.group(0)), text)
    
        2
  •  3
  •   ghostdog74    15 年前

    不需要使用regex

    >>> keys = ["cat", "dog", "mouse"]
    >>> text = "Cat dog cat cloud miracle DOG MouSE"
    >>> for w in text.split():
    ...     if w.lower() in keys:
    ...        print "[%s]%s" %(w,w.lower()),
    ...     else:
    ...        print w,
    ...
    [Cat]cat [dog]dog [cat]cat cloud miracle [DOG]dog [MouSE]mouse
    
        3
  •  1
  •   rbp zifot    15 年前

    根据您提出的解决方案,我认为我不需要将键作为列表(我将使用集合,以加快搜索速度)。这个答案还假设文本中的所有单词都被一个空格隔开(我将用这个空格将它们连接起来)。提供这些,您可以使用:

    >>> keys = (["cat", "dog", "mouse"])
    >>> text = "Cat dog cat cloud miracle DOG MouSE"
    >>> converted =  " ".join(("[%s](%s)" % (word, word.lower()) if word.lower() in keys else word) for word in text.split())
    >>> converted
    '[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](dog) [MouSE](mouse)'
    

    当然,这会调用两次word.lower()。您可以使用两个列表理解(或者实际上是生成器表达式)来避免这种情况(并且仍然使用类似的方法):

    >>> converted =  " ".join(("[%s](%s)" % (word, lower) if lower in keys else word) for word, lower in ((w, w.lower()) for w in text.split()))
    >>> converted
    '[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](dog) [MouSE](mouse)'