【发布时间】:2015-07-19 14:01:53
【问题描述】:
我有这样的句子:
((wouldyou)) give me something ((please))
还有一堆关键字,存储在数组/列表中:
keywords["wouldyou"] = ["can you", "would you", "please"]
keywords["please"] = ["please", "ASAP"]
我想用存储在数组中的一组合适的字符串替换括号中出现的每个变量,并返回所有可能的组合。变量和关键字的数量未定义。
James helped me 使用以下代码:
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))', ''))
它很好用,但只会用空字符串替换一个特定的变量。现在我想用不同的关键字来处理各种变量。期望的结果应该是这样的:
can you give me something please
would you give me something please
please give me something please
can you give me something ASAP
would you give me something ASAP
please give me something ASAP
我猜这与to_ch有关,但我不知道如何通过这个地方的列表项进行比较。
【问题讨论】:
标签: python string replace iteration combinations