Skip to main content
 首页 » 编程设计

python之有条件地替换字符串

2024年11月01日27JustinYoung

所以我可能有一个字符串 'Bank of China' 或 'Embassy of China' 和 'International China'

我想替换所有国家实例,除非我们有“of”或“of the”

显然,这可以通过遍历国家列表来完成,检查名称是否包含国家,然后检查国家“of”或“of the”之前是否存在。

如果这些确实存在,那么我们不会删除该国家/地区,否则我们会删除该国家/地区。示例将变为:

“中国银行”或“中国大使馆”和“国际”

但是,迭代可能会很慢,尤其是当您有大量国家/地区列表和大量要替换的文本列表时。

是否有更快、更基于条件的替换字符串的方法?这样我仍然可以使用 Python re 库进行简单的模式匹配?

我的功能是沿着这些路线:

def removeCountry(name): 
    for country in countries: 
        if country in name: 
            if 'of ' + country in name: 
                return name 
            if 'of the ' + country in name: 
                return name 
            else: 
                name =  re.sub(country + '$', '', name).strip() 
                return name 
    return name 

编辑:我确实找到了一些信息 here .这确实描述了如何做一个 if,但我真的想要一个 如果不是“的” 如果不是“的” 然后替换...

请您参考如下方法:

您可以编译几组正则表达式,然后通过它们传递您的输入列表。就像是: 导入重新

countries = ['foo', 'bar', 'baz'] 
takes = [re.compile(r'of\s+(the)?\s*%s$' % (c), re.I) for c in countries] 
subs = [re.compile(r'%s$' % (c), re.I) for c in countries] 
 
def remove_country(s): 
    for regex in takes: 
        if regex.search(s): 
            return s 
    for regex in subs: 
        s = regex.sub('', s) 
    return s 
 
print remove_country('the bank of foo') 
print remove_country('the bank of the baz') 
print remove_country('the nation bar') 
 
''' Output: 
    the bank of foo 
    the bank of the baz 
    the nation 
''' 

这里看起来没有比线性时间复杂度更快的东西了。至少你可以避免重新编译正则表达式一百万次并提高常数因子。

编辑:我有一些错别字,但基本思想是合理的并且有效。我添加了一个示例。