Extract parent and child node from python tree

2024/11/14 11:12:11

I am using nltk's Tree data structure.Below is the sample nltk.Tree.

(S(S(ADVP (RB recently))(NP (NN someone))(VP(VBD mentioned)(NP (DT the) (NN word) (NN malaria))(PP (TO to) (NP (PRP me)))))(, ,)(CC and)(IN so)(S(NP(NP (CD one) (JJ whole) (NN flood))(PP (IN of) (NP (NNS memories))))(VP (VBD came) (S (VP (VBG pouring) (ADVP (RB back))))))(. .))

I am not aware of nltk.Tree datastructure. I want to extract the parent and the super parent node for every leaf node e.g. for 'recently' I want (ADVP, RB), and for 'someone' it is (NP, NN)This is the final outcome i want.Earlier answer used eval() function to do so which i want to avoid.

[('ADVP', 'RB'), ('NP', 'NN'), ('VP', 'VBD'), ('NP', 'DT'), ('NP', 'NN'), ('NP', 'NN'), ('PP', 'TO'), ('NP', 'PRP'), ('S', 'CC'), ('S', 'IN'), ('NP', 'CD'), ('NP', 'JJ'), ('NP', 'NN'), ('PP', 'IN'), ('NP', 'NNS'), ('VP', 'VBD'), ('VP', 'VBG'), ('ADVP', 'RB')]
Answer

Python code for the same without using eval function and using nltk tree datastructure

sentences = " (S(S
(ADVP (RB recently))
(NP (NN someone))
(VP(VBD mentioned)(NP (DT the) (NN word) (NN malaria))(PP (TO to) (NP (PRP me)))))(, ,)(CC and)(IN so)(S(NP(NP (CD one) (JJ whole) (NN flood))(PP (IN of) (NP (NNS memories))))(VP (VBD came) (S (VP (VBG pouring) (ADVP (RB back))))))(. .))"print list(tails(sentences))def tails(items, path=()):
for child in items:if type(child) is nltk.Tree:if child.label() in {".", ","}:  # ignore punctuationcontinuefor result in tails(child, path + (child.label(),)):yield resultelse:yield path[-2:]
https://en.xdnf.cn/q/120497.html

Related Q&A

Click button with selenium and python

Im trying to do web scraping with python on and Im having trouble clicking buttons. Ive tried 3 different youtube videos using Xpath, driver.find_element_by_link_text, and driver.find_element. What am …

Combinations of DataFrames from list

I have this:dfs_in_list = [df1, df2, df3, df4, df5]I want to concatenate all combinations of them one after the other (in a loop), like:pd.concat([df1, df2], axis=1) pd.concat([df1, df3], axis=1) p…

Python: iterate through dictionary and create list with results

I would like to iterate through a dictionary in Python in the form of:dictionary = {company: {0: apple,1: berry,2: pear},country: {0:GB,1:US,2:US} }To grab for example: every [company, country] if coun…

Jira Python: Syntax error appears when trying to print

from jira.client import jiraoptions = {server: https://URL.com} jira = JIRA(options, basic_auth=(username, password))issues = jira.search_issues(jqlquery) for issue in issues:print issueI want to print…

Matplotlib plt.xlim([x_min,x_max]), list object not callable

I want to plot a scatterplot, but set the x-label limits.axScatter = plt.subplot(111) axScatter.scatter(x=mean_var_r["Variance"],y=mean_var_r["Mean"]) xlim = [-0.003, 0.003] plt.xli…

Map column birthdates in python pandas df to astrology signs

I have a dataframe with a column that includes individuals birthdays. I would like to map that column to the individuals astrology sign using code I found (below). I am having trouble writing the code …

How to use python pandas to find a specific string in various rows

I am trying to do my taxes. I have over 2,000 rows of data in a CSV of orders. I am trying to just count and print the rows that contain "CA" so I know the ones I need to pay sales tax on. I …

How to cast a list to a dictionary

I have a list as a input made from tuples where the origin is the 1st object and the neighbour is the 2nd object of the tuple. for example :inp : lst = [(a,b),(b,a),(c,),(a,c)] out : {a: (a, [b, c]), …

Couldnt get rid of (_tkinter.TclError: bad event type or keysym UP) problem

I am running a Linux mint for the first time . I tried coding a python problem but for two days I am continiously facing problems due to Linux interface please This is my code:-import turtleimport time…

WMI lib to start windows service remotely

How do I start a service using the WMI library? The code below throws the exception: AttributeError: list object has no attribute StopServiceimport wmi c = wmi.WMI (servername,user=username,password=p…