簡體   English   中英

NLTK-從概率上下文無關語法(PCFG)生成文本

[英]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。

希望你能幫幫我!

nltk.parse.generate.generate不會產生隨機句子。 它返回一個迭代器,該迭代器精確地生成每個可能的句子一次,直到生成請求數量的句子為止。 可以限制最大派生深度,但是生成是深度優先的。 它不按派生深度對句子排序。

您可以在這里找到源代碼 不難看出它在做什么。

因此,它完全是確定性的,永遠不會重復。 如果您想要(可能是無限的)隨機選擇的句子流,則必須編寫自己的生成器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM