如何在Python中检查EOF? [复制]

2023-12-27

如何在 Python 中检查 EOF?我在代码中发现了一个错误,其中分隔符后的最后一个文本块未添加到返回列表中。或者也许有更好的方式来表达这个功能?

这是我的代码:

def get_text_blocks(filename):
    text_blocks = []
    text_block = StringIO.StringIO()
    with open(filename, 'r') as f:
        for line in f:
            text_block.write(line)
            print line
            if line.startswith('-- -'):
                text_blocks.append(text_block.getvalue())
                text_block.close()
                text_block = StringIO.StringIO()
    return text_blocks

您可能会发现使用以下方法更容易解决此问题itertools.groupby http://docs.python.org/library/itertools.html#itertools.groupby.

def get_text_blocks(filename):
    import itertools
    with open(filename,'r') as f:
        groups = itertools.groupby(f, lambda line:line.startswith('-- -'))
        return [''.join(lines) for is_separator, lines in groups if not is_separator]

另一种选择是使用正则表达式 http://www.amk.ca/python/howto/regex/匹配分隔符:

def get_text_blocks(filename):
    import re
    seperator = re.compile('^-- -.*', re.M)
    with open(filename,'r') as f:
        return re.split(seperator, f.read())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Python中检查EOF? [复制] 的相关文章

随机推荐