重构python:替换字符串列表中的单词列表

时间:2013-01-18 22:43:12

标签: python regex refactoring

仍然关注python,我想知道这个功能是否可以在性能或可读性方面得到改善?

def multi_replace_words(sentences, words, replace_str):
    """Replace all words in the sentences list with replace_str
    ex. multi_replace_words(['bad a list', 'og bad', 'in bady there bad2', 'another one', 'and bad. two'], ['bad','bad2']', 'EX')
    >> ['EX a list', 'og EX', 'in bady there EX','another one','and EX two']
    """
    docs = []
    for doc in sentences:
        for replace_me in words:
            if(replace_me in doc.encode('ascii', 'ignore')):
                doc = re.sub('((\A|[^A-Za-z0-9_])'+replace_me+'(\Z|[^A-Za-z0-9_]))', ' ' + replace_str+' ', doc)
        docs.append(doc)
    return docs

谢谢:)

2 个答案:

答案 0 :(得分:1)

这样的事情:

In [86]: def func(lis,a,b):
    strs= "|".join("({0}{1}{2})".format(r'\b',x,r'\b[;",.]?') for x in a)
    for x in lis:
        yield re.sub(strs,b,x)
   ....:         

In [87]: lis
Out[87]: ['bad a list', 'og bad', 'in bady there bad2', 'another one', 'and bad. two']

In [88]: rep=['bad','bad2']

In [89]: st="EX"

In [90]: list(func(lis,rep,st))
Out[90]: ['EX a list', 'og EX', 'in bady there EX', 'another one', 'and EX two']

In [91]: rep=['in','two','a']

In [92]: list(func(lis,rep,st))
Out[92]: ['bad EX list', 'og bad', 'EX bady there bad2', 'another one', 'and bad. EX']

答案 1 :(得分:0)

您可以尝试使用replace()。它作用于字符串,并将一系列字符的所有实例替换为另一个字符。 here中的示例显示了替换行为的方式。

#!/usr/bin/python

str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);