【问题标题】:Multiple re.sub() statements多个 re.sub() 语句
【发布时间】:2012-07-19 16:20:16
【问题描述】:

在我的程序中,用户输入一个术语,我在发送之前处理该术语。此过程的一部分是将“and”、“or”和“not”的所有实例更改为大写字母,但其余部分保持不变。

我不能使用string.upper(),因为它将所有内容都更改为大写;或string.replace() 因为如果'and'在字符串中的另一个单词中,例如'salamander' 它也会将其更改为 'salamANDer'。我认为我最好的选择是正则表达式re.sub() 函数。这使我可以更改完美的完整单词。下一个问题:我必须为我想要做的每一个改变做一个re.sub() 函数。是否可以发表一份声明来完成所有更改?我所做的并没有错,但我认为它不一定是好的做法:

>>import urllib2
>>import re
>>query = 'Lizards and Amphibians not salamander or newt'
>>query=re.sub(r'\bnot\b', 'NOT',query)
>>query=re.sub(r'\bor\b', 'OR',query)
>>query=re.sub(r'\band\b', 'AND',query)
>>query = urllib2.quote("'"+query+"'")

>>print query
%27Lizards%20AND%20Amphibians%20NOT%20salamander%20OR%20newt%27

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    您可以在re.sub() 中传递函数替换表达式:

    >>> term = "Lizards and Amphibians not salamander or newt"
    >>> re.sub(r"\b(not|or|and)\b", lambda m: m.group().upper(), term)
    'Lizards AND Amphibians NOT salamander OR newt'
    

    但是,我可能会使用非正则表达式解决方案:

    >>> " ".join(s.upper() if s.lower() in ["and", "or", "not"] else s
    ...          for s in term.split())
    'Lizards AND Amphibians NOT salamander OR newt'
    

    这也规范了空格并适用于混合大小写的单词,如And

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多