仍然让我的头围绕python,我想知道这个函数是否可以提高性能或可读性?重构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
谢谢:)
我会开始将ds和cls重命名为稍微更具描述性的参数名称。 –
你是对的。我只是改变了变量名称,以更好地表示函数的目的,从ds,cls到句子,单词。他们只是我应用程序中数据集和类的简称(如nlp中的功能)。 – Sofia
不要保留标点符号吗? –