파일을 여는 iterator 클래스를 작성했습니다 (__init__
).Python 커스텀 반복자 : StopIteration에서 파일 닫기
def __init__(self, path):
self.file = open(path, "r")
반복이 완료되면 어떻게 자동으로 닫으나요?
전체 클래스 :
class Parse(object):
"""A generator that iterates through a CC-CEDICT formatted file, returning
a tuple of parsed results (Traditional, Simplified, Pinyin, English)"""
def __init__(self, path):
self.file = open(path, "r")
def __iter__(self):
return self
def __is_comment(self, line):
return line.startswith("#")
def next(self):
#This block ignores comments.
line = self.file.readline()
while line and self.__is_comment(line):
line = self.file.readline()
if line:
working = line.rstrip().split(" ")
trad, simp = working[0], working[1]
working = " ".join(working[2:]).split("]")
pinyin = working[0][1:]
english = working[1][1:]
return trad, simp, pinyin, english
else:
raise StopIteration()
반복 부분을 공유 할 수 있습니까? '.next()'또는'.__ next __()'메소드를 사용합니까, 아니면 생성자 메소드 인'__iter__'입니까? –
@MartijnPieters 전체를 공유하겠습니다. – jsj