如何使用NLTK从诱导语法中生成句子?

时间:2013-02-21 18:27:37

标签: python nlp nltk

我有一个(大)解析句子列表(使用斯坦福解析器解析),例如,句子“现在你可以被娱乐”有以下树:

(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并生成句子的任何其他工具?

5 个答案:

答案 0 :(得分:13)

在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()更好的采样方法,这隐含地假设当前节点的所有扩展都是等概率的。

答案 1 :(得分:4)

首先,如果你生成随机句子,它们可能在语义上是正确的,但它们可能会失去意义。

(听起来有点像麻省理工学院的学生用SCIgen program做的自动生成科学论文。非常有趣btw。)

无论如何,我自己从来没有这样做,但似乎有可能使用nltk.bigrams,您可以在使用Bigrams生成随机文本have a look there

你也可以generate all subtrees of a current tree,我不确定它是否是你想要的。

答案 2 :(得分:2)

使用nltk Text对象,您可以在其上调用“generate()”,这将“打印使用trigram语言模型生成的随机文本。”http://nltk.org/_modules/nltk/text.html

答案 3 :(得分:2)

我从现有的nltk.CFG语法生成随机句子的解决方案:

def generate_sample(grammar, prod, frags):        
    if prod in grammar._lhs_index: # Derivation
        derivations = grammar._lhs_index[prod]            
        derivation = random.choice(derivations)            
        for d in derivation._rhs:            
            generate_sample(grammar, d, frags)
    elif prod in grammar._rhs_index:
        # terminal
        frags.append(str(prod))

现在可以使用它:

frags = []  
generate_sample(grammar, grammar.start(), frags)
print( ' '.join(frags) )

答案 4 :(得分:0)

受上述启发,这是一种使用迭代而不是递归的方法。

import random

def rewrite_at(index, replacements, the_list):
    del the_list[index]
    the_list[index:index] = replacements

def generate_sentence(grammar):
    sentence_list = [grammar.start()]
    all_terminals = False
    while not all_terminals:
        all_terminals = True
        for position, symbol in enumerate(sentence_list):
            if symbol in grammar._lhs_index:
                all_terminals = False
                derivations = grammar._lhs_index[symbol]
                derivation = random.choice(derivations) # or weighted_choice(derivations) if you have a function for that
                rewrite_at(position, derivation.rhs(), sentence_list)
    return sentence_list

或者,如果您想要派生树,则为一。

from nltk.tree import Tree

def tree_from_production(production):
    return Tree(production.lhs(), production.rhs())

def leaf_positions(the_tree):
    return [the_tree.leaf_treeposition(i) for i in range(len(the_tree.leaves()))]

def generate_tree(grammar):
    initial_derivations = grammar._lhs_index[grammar.start()]
    initial_derivation = random.choice(initial_derivations) # or weighed_choice if you have that function
    running_tree = tree_from_production(initial_derivation)
    all_terminals = False
    while not all_terminals:
        all_terminals = True
        for position in leaf_positions(running_tree):
            node_label = running_tree[position]
            if node_label in grammar._lhs_index:
                all_terminals = False
                derivations = grammar._lhs_index[node_label]
                derivation = random.choice(derivations) # or weighed_choice if you have that function
                running_tree[position] = tree_from_production(derivation)
    return running_tree

以下是用于上述的NLTK PCFG生产规则的weighted_choice函数,该函数改编自Ned Batchelder对here的一般加权选择函数的回答:

def weighted_choice(productions):
    prods_with_probs = [(prod, prod.prob()) for prod in productions]
    total = sum(prob for prod, prob in prods_with_probs)
    r = random.uniform(0, total)
    upto = 0
    for prod, prob in prods_with_probs:
        if upto + prob >= r:
            return prod
        upto += prob
    assert False, "Shouldn't get here"