gpt4 book ai didi

python - 在 Python 中扩展组合集?

转载 作者:行者123 更新时间:2023-11-28 20:38:33 24 4
gpt4 key购买 nike

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

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

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 应用程序执行此操作,因为它不接受用于自然语言处理的正则表达式(为什么!?)。

提前致谢。

最佳答案

您可能需要的是 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?

关于python - 在 Python 中扩展组合集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40979747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com