python - Using itertools with a generator class -



python - Using itertools with a generator class -

i'm trying write class generates words file programme reads in. i'm stuck __iter__ , next methods. thought read in file in __init__ i'm confused how iterate on because know itertools doing similar. advice?

currently have code.

def __init__(self): self.words = [] self.n = 0 open('words.txt') f: text = f.read() x in text.split(): if len(x) > 2 , x[0].islower(): self.words.append(x) def __iter__(self): homecoming self def next(self): if(self.n == 0): self.n = self.n + 1 homecoming self.words[0] else: self.n = self.n + 1 homecoming self.words[self.n-1]

this how code should run.

>>> mw = merriamwebster() >>> [w w in itertools.islice(mw, 5)] ['aal', 'aalii', 'aam', 'aardvark', 'aardwolf']

the __iter__ method in case needs homecoming object keeps track of it's position.

if __iter__ returns self, track position in instance variable, it's mixing 2 responsibilities, , means can't have 2 (or more) independent iterators on object. can create sense in cases though.

it looks want generator here

def merriamwebster(fname='words.txt'): open(fname) f: x in f: if len(x) >= 2: yield x

python

Comments

Popular posts from this blog

c - Compilation of a code: unkown type name string -

java - Bypassing "final local variable defined in an enclosing type" -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -