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

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

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

How to convert the parsedSentence type to a list (tree) and access the 1st element of this list.

I already tried list(parser.raw_parse_sents([sentence],False)) , but did not convert the result to a list.

Edited by:

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

Here it gives an error:

 'listiterator' object has no attribute 'treepositions' 

Thanks.

+5
source share
2 answers

It doesn't matter how many times you used iter on an iterable object, you can just convert it to a list by calling the 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 first element, you don't need to use the list function, you can just use the next method for an iterator or the next() built-in function (in python 3.X you can just use the next() built-in function) to get the element forst:

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

Now about your problem, if you did not get list after calling list after calling it, of course, this is not an iterator, it would be another type of object that you need to get so that its elements are based on how its __getitem__ .

Based on your edit, t1 is a list iterator object and does not have a treepositions attribute, you can treepositions over its elements and then call the treepositions tag:

 s1 = parsedSentence[0] t1 = Tree.convert(s1) positions = [item.treepositions() for item in t1] 
+2
source

Finally, the problem was resolved by changing

 parser.raw_parse_sents([sentence],False) 

to

 parser.raw_parse(sentence) 

Thanks to everyone who contributed their time.

+1
source

Source: https://habr.com/ru/post/1233060/


All Articles