传递谓词怎么样?
def per_section(it, is_delimiter=lambda x: x.isspace()): ret = [] for line in it: if is_delimiter(line): if ret: yield ret # OR ''.join(ret) ret = [] else: ret.append(line.rstrip()) # OR ret.append(line) if ret: yield ret
用法:
with open('/path/to/file.txt') as f: sections = list(per_section(f)) # default delimiterwith open('/path/to/file.txt.txt') as f: sections = list(per_section(f, lambda line: line.startswith('#'))) # comment


