gpt4 book ai didi

ruby - 从 map 创建字符串

转载 作者:数据小太阳 更新时间:2023-10-29 07:24:28 25 4
gpt4 key购买 nike

我目前正在开展一个项目,通过使用上下文无关语法规则,我将生成随机句子。现在,我正在创建一个函数,该函数将接受一个散列,并遍历它选择正确的产品来创建一个句子并将其作为字符串返回。

例如,给定以下格式的散列:

{
"<start>"=>[["The", "<object>", "<verb>", "tonight."]],
"<object>"=>[["waves"], ["big", "yellow", "flowers"], ["slugs"]],
"<verb>"=>[["sigh", "<adverb>"], ["portend", "like", "<object>"], ["die", "<adverb>"]],
"<adverb>"=>[["warily"], ["grumpily"]]
}

我应该能够生成一个随机句子,例如:“The waves die grumpily tonight”。

下面是生成这句话的整体过程:

  1. 它将始终在 <start> 开始生成标记并继续填写所需的作品。
  2. 它通过 <start>并添加“The”然后遇到“<object>”所以它进入<object> key 并从那里获取一个随机值,例如 ["waves"] .
  3. 然后它返回并继续遍历并遇到“<verb>”所以它进入<verb> key 并从那里获取一个随机值,例如 ["die", "<adverb>"] .
  4. 因为它遇到了“<adverb>”,它必须进入<adverb>键并选择一个随机值,例如 ["grumpily"]。
  5. 然后它返回遍历,遇到并添加“今晚”。已经到了<start>的结尾所以它现在可以输出句子了。

如何编写随机生成句子的方法?

最佳答案

有趣的练习!

定义字符串后#has_placeholder?检查 < 和 >

之间的单词

只要有占位符,算法就会选择一个起始句并对其进行迭代。如果找到占位符,它将被随机选择的子句替换。没有做任何检查错误的事情。某些占位符可能未定义或可能存在无限循环。

它返回一个字符串,它也可以返回一个包含不同深度数组的树。

class String
def has_placeholder?
self=~/<\w+>/
end
end

grammar = {
"<start>"=>[["The", "<object>", "<verb>", "tonight."]],
"<object>"=>[["waves"], ["big", "yellow", "flowers"], ["slugs"]],
"<verb>"=>[["sigh", "<adverb>"], ["portend", "like", "<object>"], ["die", "<adverb>"]],
"<adverb>"=>[["warily"], ["grumpily"]]
}


sentence = grammar["<start>"].sample.join(' ')

while sentence.has_placeholder? do
puts sentence
sentence.sub!(/(<\w+>)/){grammar[$1].sample.join(' ')}
end

puts sentence

输出:

The <object> <verb> tonight.
The slugs <verb> tonight.
The slugs portend like <object> tonight.
The slugs portend like slugs tonight.

The <object> <verb> tonight.
The big yellow flowers <verb> tonight.
The big yellow flowers portend like <object> tonight.
The big yellow flowers portend like slugs tonight.

编辑:

您想要的方法可能如下所示:

def expand(grammar, nonterm = "<start>")
sentence = grammar[nonterm].sample.join(' ')
while sentence.has_placeholder? do
sentence.sub!(/(<\w+>)/){grammar[$1].sample.join(' ')}
end
sentence
end

关于ruby - 从 map 创建字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40333829/

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