Q:

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 (i i))) (VERB_MD (pt_verb_md need)) (NP_NN (ADJ_AT (a a)) (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 doesnt work.  What am I missing or doing wrong? 

A:

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)

