简体   繁体   中英

PCFG generation in NLTK

I am trying to learn a PCFG from a file containing parse trees for example:

(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))

This is my relevant code:

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!")

Now after that I've tried SO much stuff on the internet for example:

grammar = induce_pcfg(S, productions)

but here the productions is always the built in functions, for example:

productions = []
for item in treebank.items[:2]:
  for tree in treebank.parsed_sents(item):
    productions += tree.productions()

I've tried replacing production here with treeData in my case, but it doesn't work. What am I missing or doing wrong?

Start with building trees:

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

Then you can extract Probabilistic-CFG (PCFG) like this:

from nltk import induce_pcfg

S = Nonterminal('S')
grammar_PCFG = induce_pcfg(S, treeData_rules)
print(grammar_PCFG)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM