سؤال

I'm trying to create an iterator that extracts every word from a text file and iterates through them. This is what I have right now:

class String_iterator:
    def __init__(self, filename):
        self.words = []
        f = open(filename, 'r')
        lines = f.readlines()
        for line in lines:
            self.words.extend(line.split(" "))
        self.ind = 0
        self.size = len(self.words)

    def __iter_(self):
        return self

    def next(self):
        if self.ind > self.size:
            raise StopIteration
        else:
            self.ind += 1
            return self.words[self.ind-1]

Comparing it to functional simple examples of Python iterators, I can't figure out why it isn't working when I try to use it in even a simple case:

sit = String_iterator(filename)
for word in sit:
    print word

I get the error:

Traceback (most recent call last):
  File "WordCounter.py", line 68, in <module>
    for word in sit:
TypeError: iteration over non-sequence

I am guessing that there is something wrong with the String_iterator that it's not a proper iterator, but I can't figure out what.

(I'm also having issues with the encoding on reading in the file, but that's another issue altogether...)

هل كانت مفيدة؟

المحلول

You forgot an underscore:

def __iter_(self):
# ---------^

Python won't recognise your custom class as an iterator unless you use the correct name:

def __iter__(self):
    return self
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top