これは、行を読んで分割する必要を回避する、完全に機能的なアプローチです。モジュールを利用しitertools
ます:
Python 3 の場合は、次のように置き換えitertools.imap
てください。map
import itertools
def readwords(mfile):
byte_stream = itertools.groupby(
itertools.takewhile(lambda c: bool(c),
itertools.imap(mfile.read,
itertools.repeat(1))), str.isspace)
return ("".join(group) for pred, group in byte_stream if not pred)
使用例:
>>> import sys
>>> for w in readwords(sys.stdin):
... print (w)
...
I really love this new method of reading words in python
I
really
love
this
new
method
of
reading
words
in
python
It's soo very Functional!
It's
soo
very
Functional!
>>>
あなたの場合、これは関数を使用する方法だと思います:
with open('words.txt', 'r') as f:
for word in readwords(f):
print(word)