Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - NLP - convert iter(iter(tree)) to list(tree)

I have a parser function which returns iter(iter(tree)).

parsedSentence = parser.raw_parse_sents([sentence],False)  

How can I convert the parsedSentence type to list(tree) and access 1st element of that list.

I've already tried list(parser.raw_parse_sents([sentence],False)) but it's not converting the result to list.

Edited:

s1 = parsedSentence[0]
t1 = Tree.convert(s1)
positions = t1.treepositions()

Here it throws an error:

'listiterator' object has no attribute 'treepositions'

Thank You.

like image 223
Alekhya Vemavarapu Avatar asked Oct 19 '22 01:10

Alekhya Vemavarapu


1 Answers

It doesn't make any difference that how many time you used iter on an iterable object you can simply convert it to list by calling list function.

>>> l =[6, 3, 5, 1, 4, 2]
>>> list(iter(iter(iter(iter(l)))))
[6, 3, 5, 1, 4, 2]

But if you just want to get the fist item you don't need to use list function you can simply use next method on an iterator or next() built-in function (in python 3.X you can just use built-in function next()) to get the forst item :

>>> iter(iter(l)).next()
6
>>> iter(iter(iter(l))).next()
6
>>> iter(iter(iter(iter(l)))).next()
6

Now about your problem if you didn't get a list after calling list after calling it surely it's not an iterator it would be another object type that you need to get its items based on how its __getitem__ method has been implemented.

Based on your edit t1 is a list iterator object and doesn't has attribute treepositions you can loop over it's items and then call those treepositions attribute:

s1 = parsedSentence[0]
t1 = Tree.convert(s1)
positions = [item.treepositions() for item in t1]
like image 195
Mazdak Avatar answered Nov 03 '22 07:11

Mazdak