我甚至不确定如何用文字解释我想要做什么,所以我将使用例子:
我想在字符串中使用一组选项,如下所示(如果这样更容易,格式可以改变):
is (my|the) car (locked|unlocked) (now)?
Run Code Online (Sandbox Code Playgroud)
并让它吐出以下字符串列表:
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
Run Code Online (Sandbox Code Playgroud)
我需要能够为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))
Run Code Online (Sandbox Code Playgroud)
这打印:
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?
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
167 次 |
| 最近记录: |