Python 3.2:如何使用多组线将多行字符串拆分为多个部分

时间:2011-11-06 04:44:55

标签: regex python-3.x

我有一个跨多行数据组的文件。数据行的每一部分前面都有两行,以哈希标记(#)开头,后跟一行换行符('\ 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如何处理它们)的理解中缺少哪些内容可以帮助我看到解决方案?

1 个答案:

答案 0 :(得分: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'