扩展 Python 中的一组组合?

Expand set of combinations in Python?

我什至不确定如何用语言解释我想做的事情,所以我将使用示例:

我想在一个字符串中获取一组选项,像这样(如果这样更容易,格式可以改变):

is (my|the) car (locked|unlocked) (now)?

并让它吐出以下字符串列表:

is my car locked
is the car locked
is my car unlocked
is the car unlocked
is my car locked now
is the car locked now
is my car unlocked now
is the car unlocked now

我需要能够为 Alexa 应用程序执行此操作,因为它不接受用于自然语言处理的正则表达式(为什么!?)。

提前致谢。

您可以使用 Spintax.

Spintax (also known as spin syntax) is a way to create random strings that have the same or similar meaning.

Simple example:

"{Hey|Hello|Hi} this is {spin syntax|spintax}{.|!|}" Can produce:

Hey this is spintax.
Hi this is spin syntax
Hello this is spintax
Hi this is spintax!

您可能想要的是 itertools.product()。例如,您可以这样使用它:

import itertools

# set up options
opt1 = ["my", "the"]
opt2 = ["locked", "unlocked"]
opt3 = [" now", ""] # You'll have to use an empty string to make something optional

# The sentence you want to template
s = "is {} car {}{}?"

# Do all combinations
for combination in itertools.product(opt1, opt2, opt3):
    print(s.format(*combination))

这会打印:

is my car locked now?
is my car locked?
is my car unlocked now?
is my car unlocked?
is the car locked now?
is the car locked?
is the car unlocked now?
is the car unlocked?