Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from Tree type to String type in Python by nltk?

for subtree3 in tree.subtrees():
  if subtree3.label() == 'CLAUSE':
    print(subtree3)
    print subtree3.leaves()

Using this code I able to extract the leaves of the tree. Which are: [('talking', 'VBG'), ('constantly', 'RB')] for a certain example. That is perfectly correct. Now I want this Tree elements to convert into string or in list for some further processing. How can I do that?

What I tried

for subtree3 in tree.subtrees():
  if subtree3.label() == 'CLAUSE':
    print(subtree3)
    print subtree3.leaves()
    fo.write(subtree3.leaves())
fo.close()

But it throws an error :

Traceback (most recent call last):
  File "C:\Python27\Association_verb_adverb.py", line 35, in <module>
    fo.write(subtree3.leaves())
TypeError: expected a character buffer object

I just want to store the leaves in a text file.

like image 503
Salah Avatar asked May 12 '26 18:05

Salah


1 Answers

It depends on your version of NLTK and Python. I think you're referencing the Tree class in the nltk.tree module. If so, read on.

In your code, it's true that:

  1. subtree3.leaves() returns a "list of tuple" object and,
  2. fo is a Python File IO object, the fo.write only receives a str type as a parameters

you can simply print the tree leaves with fo.write(str(subtree3.leaves())), thus:

for subtree3 in tree.subtrees():
    if subtree3.label() == 'CLAUSE':
        print(subtree3)
        print subtree3.leaves()
        fo.write(str(subtree3.leaves()))
fo.flush()
fo.close()

and don't forget to flush() the buffer.

like image 84
lguiel Avatar answered May 15 '26 06:05

lguiel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!