iter 无法运行。我只想打印目录/ tmp中每个文件的所有单词。
class CorpusReader:
def __init__(self, dirname):
self.dirname = dirname;
def __iter__(self):
for fname in os.listdir(self.dirname):
for line in open(os.path.join(self.dirname,fname)):
yield line.split()
reader = CorpusReader("/tmp")
答案 0 :(得分:3)
您需要的是遍历reader
:
for line in reader:
print line
请记住,并非所有文件都是可读的,您需要防范这种情况:
def __iter__(self):
for fname in os.listdir(self.dirname):
try:
for line in open(os.path.join(self.dirname,fname)):
yield line.split()
except IOError:
pass # or handle this error, most likely due to file not readable
答案 1 :(得分:1)
第二个函数__iter__
允许类CorpusReader
的对象可迭代。这意味着您可以在for循环(或其他可迭代方法)中迭代它。要打印所有文件,请执行此操作
for i in reader:
print(i)