【问题标题】:Expand set of combinations in Python?在 Python 中扩展组合?
【发布时间】:2016-12-05 17:16:35
【问题描述】:

我什至不知道如何用语言来解释我要做什么,所以我将使用示例:

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

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

提前致谢。

【问题讨论】:

  • 你“可以使用的是{0}汽车{1}锁定{2}吗?”.format(a, b, c)

标签: python alexa


【解决方案1】:

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

【讨论】:

  • 将其与 Spintax 的 RegExp 一起使用,您将获得所需的一切。
  • itertools 让我惊喜不断
【解决方案2】:

您可以使用Spintax

Spintax(也称为自旋语法)是一种创建具有相同或相似含义的随机字符串的方法。

简单示例:

"{Hey|Hello|Hi} this is {spin syntax|spintax}{.|!|}" 可以产生:

嘿,这是 spintax。
嗨,这是自旋语法
您好,这是 spintax
嗨,这是 Spintax!

【讨论】:

  • 如何让一个元素成为可选元素?
猜你喜欢
  • 1970-01-01
  • 2011-03-26
  • 2010-11-25
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 2010-09-09
  • 1970-01-01
相关资源
最近更新 更多