2013-01-18 96 views
1

仍然讓我的頭圍繞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 

謝謝:)

+2

我會開始將ds和cls重命名爲稍微更具描述性的參數名稱。 –

+0

你是對的。我只是改變了變量名稱,以更好地表示函數的目的,從ds,cls到句子,單詞。他們只是我應用程序中數據集和類的簡稱(如nlp中的功能)。 – Sofia

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

你可以嘗試使用替代()。它作用於一個字符串並將一系列字符的所有實例替換爲另一個字符。來自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); 
+1

也可以替換單詞中的部分文本,就像在這個 – Sofia

+0

如果你想確保只更換完整的單詞而不創建混音,就像上面的例子一樣,你可以在引號中的單詞之前和之後添加空格。像這樣的「是」。 – JonathanV

相關問題