forked from gc3-uzh-ch/python-course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworditer.py
executable file
·47 lines (34 loc) · 1.14 KB
/
worditer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class WordIterator(object):
"""
Split the given text at white spaces,
and return the parts one by one.
"""
def __init__(self, text):
self._words = text.split()
def next(self):
if len(self._words) > 0:
return self._words.pop(0)
else:
raise StopIteration
def __next__(self):
"""Compatibility method for Python 3"""
return self.next()
def __iter__(self):
return self
## test intended usage
import unittest
class WordIteratorTest(unittest.TestCase):
def test_word_sequence(self):
witer = WordIterator("word by word iteration")
words = list(witer)
self.assertEqual(words, ['word', 'by', 'word', 'iteration'])
def test_empty_text(self):
witer = WordIterator("")
no_words = list(witer)
self.assertTrue(len(no_words) == 0)
def test_multiple_whitespace(self):
witer = WordIterator("a text with multiple spaces in it")
self.assertEqual(list(witer),
['a', 'text', 'with', 'multiple', 'spaces', 'in', 'it'])
if __name__ == "__main__":
unittest.main()