【问题标题】:Python 3.2: how to split multiline strings into sections using groups of linesPython 3.2:如何使用行组将多行字符串拆分为多个部分
【发布时间】:2011-11-06 04:44:54
【问题描述】:

我有一个跨多行的数据组文件。数据行的每一部分前面都有两行,以井号 (#) 开头,后面是换行符 ('\n')、一行破折号 ('-'),然后是另外两个换行符。

换句话说,文件看起来像这样:

# Comment
# Comment
data for section 1
data for section 1
...
last line of data for section 1

--------------------------------------------------

# Comment
# Comment
data for section 2
data for section 2
...
last line of data for section 2

--------------------------------------------------

...

我想将此文件分成以这种方式包围的每个组,以便我可以单独处理它们。由于我手头上用于文件处理的最简单的语言是 Python 3.2,因此我尝试构建一个正则表达式来执行此拆分。不幸的是,我无法进行拆分。

例如,我已成功使用以下正则表达式找到要忽略的行:

with open('original.out') as temp:
    original = temp.read()
print(re.findall(r'^$|^[#-].*$', original, re.MULTILINE))

但是当我尝试将相同的正则表达式传递给re.split() 时,它只会返回整个文件。

如何按照我需要的方式构建这个部分列表,以及我对正则表达式(或 Python 如何处理它们)的理解中缺少哪些可以帮助我找到解决方案的内容?

【问题讨论】:

    标签: regex python-3.x


    【解决方案1】:

    快速而肮脏的基于生成器的解决方案

    from collections import deque
    
    # yield each section
    def gen_sections(lines):
       breaker = deque(maxlen=3)
       section = []
       check = [
          lambda line: not line.strip(),       # blank
          lambda line: line.startswith('---'), # dashed line
          lambda line: not line.strip()        # blank
       ]
       for line in lines:
          line = line.strip()
          breaker.append(line)
          section.append(line)
          if len(breaker) == 3 and all(f(x) for f,x in zip(check, breaker)):
             yield '\n'.join(section[:-len(breaker)])
             section = []
    
    # wrap file in this to remove comments
    def no_comments(lines):
       for line in lines:
          line = line.strip()
          if not line.startswith('#'):
             yield line
    
    for section in gen_sections(open('file.txt')):
      print section, '\n'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-02
      • 2010-09-15
      • 2012-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      相关资源
      最近更新 更多