仍然对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
谢谢 :)