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.
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:
subtree3.leaves() returns a "list of tuple" object and, fo is a Python File IO object, the fo.write only receives a str type as a parametersyou 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With