2015-07-19 87 views
0

我處理字符串,每個在括號中的可選變量的動態量:蟒蛇字符串替換,產生所有可能的組合

(?please) tell me something (?please) 

現在我想用一個空字符串替換變量,並取回所有可能的變化:

tell me something (?please) 

(?please) tell me something 

tell me something 

想要的函數應該處理多個,不同的和無窮無盡的變量。

任何幫助高度讚賞。

+0

我已經嘗試了DSM http://stackoverflow.com/questions/14841652/string-replacement-combinations的代碼,但它不適用於完整的句子,不知道爲什麼。 – HSRF

回答

1

String Replacement Combinations上使用該解決方案的問題是,解決方案會迭代原始字符串中的每個字符,而您想檢查原始字符串的子字符串。因此,您應該使用字符串split()並遍歷該列表。另外,當您最後加入列表時,請將空格放回單詞之間。例如,

def filler(word, from_char, to_char):  
    options = [(c,) if c != from_char else (from_char, to_char) for c in word.split(" ")] 
    return (' '.join(o) for o in product(*options)) 
list(filler('(?please) tell me something (?please)', '(?please)', '')) 

這將返回

['(?please) tell me something (?please)', '(?please) tell me something ', ' tell me something (?please)', ' tell me something '] 

如果你想忽略不包含清除(行'(?please) tell me something (?please)')行,哈克簡單的辦法就是去掉結果的第一個元素,因爲product的工作方式可以保證第一個結果會選取每個選項的第一個元素,這對應於沒有刪除字符串的行。

+0

對不起還有一個問題:我如何用幾個不同的和可選的變量來做到這一點。在循環中迭代對我無效 – HSRF

+0

您需要修改'c!= from_char'以使其與變量列表進行比較。請嘗試一下,讓我知道它是怎麼回事。 – James

+0

你讓我做到了! 'options = [(c,)if c不在from_char else(c,to_char)for c in word.split(「」)]'謝謝 – HSRF