NLTK-从概率上下文免费语法(PCFG)生成文本



我有一个免费语法,并使用它来创建句子(在python中使用nltk)。

# Create a CFG
from nltk import CFG
from nltk.parse.generate import generate
grammar = CFG.fromstring("""
Story -> Introduction MainQuest End
LocationInfo -> 'He found himself in a small village where he grew up.'
Introduction -> 'Long ago there was a boy who decided to become a knight.'
MainQuest -> LocationInfo 'He had to get a sword first to fight monsters' Navigate
Navigate -> '[He could go west]' GoodEnd | '[He could go east]' BadEnd
GoodEnd -> 'And he lived happily ever after.'
BadEnd -> 'Finally he died painfully.'
End -> 'The End'
""")
#print(grammar.start())
#print(grammar.productions())
for sentence in generate(grammar, n=2):
    print('n'.join(sentence))
    print('n')

这很容易且有效。但是现在,我想在特殊情况下添加概率,以便基于给定概率的随机因素,我生成的故事可以具有好处或坏结局。

我找不到任何例子,当我将pcfg喂入nltk.parse.generate时,它像cfg一样对待。

希望您能帮助我!

nltk.parse.generate.generate不会产生随机句子。它返回一个迭代器,该迭代器会精确地产生每个可能的句子,直到生成所请求的句子数为止。最大推导深度可以受到限制,但生成是深度优先。它不会通过派生深度订购句子。

您可以在此处找到源代码;不难看到它在做什么。

因此,它完全是确定性的,永远不会重复自己。如果您想要(可能无限的)随机选择的句子流,则必须编写自己的发电机。

最新更新