我有一个(大)解析句子列表(使用斯坦福解析器解析),例如,句子“现在你可以娱乐了”有以下树:
(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 来执行此操作,是否存在任何其他工具可以接受(可能重新格式化)grammar
并生成句子?
在NLTK 2.0中你可以使用nltk.parse.generate
生成all可能的给定语法的句子 http://nltk.org/_modules/nltk/parse/generate.html.
此代码定义了一个函数,该函数应根据 (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()
,它隐含地假设当前节点的所有扩展都是等概率的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)