admin 管理员组

文章数量: 1087747

python自动生成中文句子

在NLTK 2.0中,可以使用nltk.parse.generate生成all可能的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自动生成中文句子