![](/img/trans.png)
[英]Python Context Free Grammar and PCFG generation benchmarks?
[英]NLTK - generate text from probabilistic context free grammar (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。
希望你能帮帮我!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.