python字符串替换,所有可能的组合#2

python字符串替换,所有可能的组合#2,python,string,replace,iteration,combinations,Python,String,Replace,Iteration,Combinations,我有如下句子: ((wouldyou)) give me something ((please)) 和一组关键字,存储在数组/列表中: keywords["wouldyou"] = ["can you", "would you", "please"] keywords["please"] = ["please", "ASAP"] 我想用数组中存储的一组合适的字符串替换括号中出现的每一个变量,并返回所有可能的组合。变量和关键字的数量未定义 James使用以下代码: def filler(wor

我有如下句子:

((wouldyou)) give me something ((please))
和一组关键字,存储在数组/列表中:

keywords["wouldyou"] = ["can you", "would you", "please"]
keywords["please"] = ["please", "ASAP"]
我想用数组中存储的一组合适的字符串替换括号中出现的每一个变量,并返回所有可能的组合。变量和关键字的数量未定义

James使用以下代码:

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
有关,但我不知道如何通过这里的列表项进行比较。

这是Regex船长的工作

部分,伪代码,解决方案

一种直接的方法是使用re模块中的regex功能匹配单词,然后使用re.sub()方法将它们替换掉,尽管效率很低(比如O(n*m),其中n是要替换的单词数,m是每个单词的平均替换数)。然后您可以将其嵌入嵌套循环中。因此(假设您首先将替换项放入dict或其他文件中),它看起来是这样的:

for key in repldict:
  regexpattern = # construct a pattern on the fly for key
  for item in repldict[key]:
    newstring = re.sub(regexpattern, item)
等等。只有,你知道,像正确的语法和东西。然后只需将新闻字符串附加到列表中,或打印它,或其他任何内容

要动态创建regexpatern,字符串连接就应该做到这一点。比如一个正则表达式来匹配左参数,再加上要匹配的字符串,再加上一个正则表达式来匹配右参数


如果您这样做,那么您只需在第二个版本的正则表达式模式上循环即可处理可选功能,该模式在左括号的末尾附加一个问号,然后执行您想执行的任何操作。

以下操作将有效。它使用
itertools.product
构建关键字的所有可能配对(或更多配对)

import re, itertools

text = "((wouldyou)) give me something ((please))"

keywords = {}
keywords["wouldyou"] = ["can you", "would you", "please"]
keywords["please"] = ["please", "ASAP"]

# Get a list of bracketed terms
lsources = re.findall("\(\((.*?)\)\)", text)

# Build a list of the possible substitutions 
ldests = []
for source in lsources:
    ldests.append(keywords[source])

# Generate the various pairings
for lproduct in itertools.product(*ldests):
    output = text
    for src, dest in itertools.izip(lsources, lproduct):
        # Replace each term (you could optimise this using a single re.sub)
        output = output.replace("((%s))" % src, dest)

    print output
您可以通过避免使用一个
re.sub()
调用执行多个
replace()
和赋值调用来进一步改进它

此脚本提供以下输出:

can you give me something please
can you give me something ASAP
would you give me something please
would you give me something ASAP
please give me something please
please give me something ASAP

它是使用Python2.7进行测试的。如果使用了多个相同的关键字,您需要考虑如何解决这个问题。希望您觉得这很有用。

非常感谢您,先生。这是难以置信的,让我了解了itertools的工作原理。我一定会努力解决你提到的问题,并报告我的进展。