简体   繁体   中英

How to get a node in a tree by its label in nltk python?

I have a tree:

(S  
    (WH-QUERY Which)  
    (FLIGHT-NP   
        (FLIGHT-CNP  
            (FLIGHT-CNP (FLIGHT-N flight))  
            (FLIGHT-DEST to (CITY-NP (CITY-NAME Hue) (CITY-N city)))))  
    (FLIGHT-VP  
        (FLIGHT-V arrives)  
        (FLIGHT-TIME (P-TIME at) (TIME-MOD 20:00HR))))  

I want to get a specific node by its label in nltk. For example, I have label "CITY-NAME", and I want to get the node (CITY-NAM Hue). How can I achieve this?

One way to do it is to walk the tree searching for nodes that match:

for subtree in tree.subtrees():
     if subtree.label() == 'CITY-NAME':
          print subtree.leaves()

Look at the _get_node method in the function.

http://www.nltk.org/_modules/nltk/tree.html

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