gpt4 book ai didi

python - 如何使用 NLTK 从归纳语法生成句子?

转载 作者:太空狗 更新时间:2023-10-29 17:04:46 26 4
gpt4 key购买 nike

我有一个(大)已解析句子列表(使用斯坦福解析器解析),例如,句子“Now you can be entertained”具有以下树:

(ROOT
(S
(ADVP (RB Now))
(, ,)
(NP (PRP you))
(VP (MD can)
(VP (VB be)
(VP (VBN entertained))))
(. .)))

我正在使用句子树集来使用 nltk 归纳语法:

import nltk

# ... for each sentence tree t, add its production to allProductions
allProductions += t.productions()

# Induce the grammar
S = nltk.Nonterminal('S')
grammar = nltk.induce_pcfg(S, allProductions)

现在我想使用 grammar 生成新的随机句子。我希望,由于语法是从一组特定的输入示例中学习的,因此生成的句子在语义上是相似的。我可以在 nltk 中这样做吗?

如果我不能使用 nltk 来执行此操作,是否存在任何其他工具可以采用(可能重新格式化的)语法 并生成句子?

最佳答案

在 NLTK 2.0 中,您可以使用 nltk.parse.generate 生成所有可能的 sentences for a given grammar .

此代码定义了一个函数,该函数应根据 (P)CFG 中的产生式规则生成单个句子。

# This example uses choice to choose from possible expansions
from random import choice
# This function is based on _generate_all() in nltk.parse.generate
# It therefore assumes the same import environment otherwise.
def generate_sample(grammar, items=["S"]):
frags = []
if len(items) == 1:
if isinstance(items[0], Nonterminal):
for prod in grammar.productions(lhs=items[0]):
frags.append(generate_sample(grammar, prod.rhs()))
else:
frags.append(items[0])
else:
# This is where we need to make our changes
chosen_expansion = choice(items)
frags.append(generate_sample,chosen_expansion)
return frags

要在 PCFG 中使用权重,您显然需要使用比 choice() 更好的采样方法,它隐含地假设当前节点的所有扩展都是等概率的。

关于python - 如何使用 NLTK 从归纳语法生成句子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15009656/

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