0

I have a Python function that traverses a sentence parsed as a tree looking for adjective/noun pairs (such as "good cat"), creates a list of such pairs, and returns it. Here it is:

def traverse(t):
     thelist = list()
     try:
         t.label()
     except AttributeError:
          return
     else:
         if t.label() == 'NP': 
             for leaf in t.leaves():
                  thelist.append(str(leaf[0]))
             print("The list is ",thelist)
             return thelist
         else:
             for child in t:
                  traverse(child)   

I call this function like so:

 print("traversing the tree returned ",traverse(pos_parser))

What I get is this:

The list is  ['good', 'cat']
traversing the tree returned  None

So it creates and prints out variable "thelist" in traverse but doesn't return it (returns None instead). Why??

Can someone please help?

user3490622
  • 939
  • 2
  • 11
  • 30

1 Answers1

0

I'm guessing that your first time through the traverse function, you are hitting the last line which recursively calls traverse. However, you don't do anything with the output of that call. My guess is that you should need to modify the last line to capture the output of the traverse calls and then ultimately return the list.

As-is, you only are calling return on your leaf-node calls.

Something like this:

def traverse(t): thelist = list() try: t.label() except AttributeError: return else: if t.label() == 'NP': for leaf in t.leaves(): thelist.append(str(leaf[0])) print("The list is ",thelist) return thelist else: for child in t: thelist.append(traverse(child)) return thelist

Cargo23
  • 3,064
  • 16
  • 25