NLTK 中的 PCFG 生成

Ray*_*y92 0 python grammar nltk

我正在尝试从包含解析树的文件中学习 PCFG,例如:

(S (DECL_MD (NP_PPSS (PRON_PPSS (ii))) (VERB_MD (pt_verb_md need)) (NP_NN (ADJ_AT (aa)) (NOUN_NN (flight flight)) (PREP_IN (pt_prep_in from))) (AVPNP_NP (NOUN_NP (charlotte charlotte) ))

这是我的相关代码:

def loadData(path):
    with open(path ,'r') as f:
        data = f.read().split('\n')
    return data

def getTreeData(data):
    return map(lambda s: tree.Tree.fromstring(s), data)

# Main script
print("loading data..")
data = loadData('C:\\Users\\Rayyan\\Desktop\\MSc Data\\NLP\\parseTrees.txt')
print("generating trees..")
treeData = getTreeData(data)
print("done!")
print("done!")
Run Code Online (Sandbox Code Playgroud)

现在之后我在互联网上尝试了很多东西,例如:

grammar = induce_pcfg(S, productions)
Run Code Online (Sandbox Code Playgroud)

但这里的产品总是内置的功能,例如:

productions = []
for item in treebank.items[:2]:
  for tree in treebank.parsed_sents(item):
    productions += tree.productions()
Run Code Online (Sandbox Code Playgroud)

在我的情况下,我试过用production这里替换treeData,但它不起作用。我错过了什么或做错了什么?

Kat*_*ina 5

从建树开始:

from nltk import tree
treeData_rules = []

# Extract the CFG rules (productions) for the sentence
for item in treeData:
    for production in item.productions():
    treeData_rules.append(production)
treeData_rules
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样提取概率CFG(PCFG):

from nltk import induce_pcfg

S = Nonterminal('S')
grammar_PCFG = induce_pcfg(S, treeData_rules)
print(grammar_PCFG)
Run Code Online (Sandbox Code Playgroud)