仍然讓我的頭圍繞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
不要保留標點符號嗎? –