python - 重构 python : replace list of words in list of strings

标签 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

谢谢:)

最佳答案

类似这样的事情:

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']

关于python - 重构 python : replace list of words in list of strings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14408846/

相关文章:

python - Seaborn 带状图和误差线

python - Ansible:根据特定事实对主机进行计数

Python- sum() 恰好需要 2 个参数(给定 1 个)

php - 理解正则表达式

Python:重构代码以删除全局变量

python - Django 如何在 View 中保存模型

来自字符串的 Php 正则表达式 "deleting only one charactered words"

algorithm - 数字的分解优化

Python:如何保持与实例的独立性?

r - 匹配字符后跟恰好 1 位数字