如何在Python中基于注释块分割文本文件?

如何在Python中基于注释块分割文本文件?,python,parsing,Python,Parsing,我浪费了早上的大部分时间没能解决这个简单的问题。使用python,我想解析如下所示的数据文件: # This is an example comment line, it starts with a '#' character. # There can be a variable number of comments between each data set. # Comments "go with" the data set that comes after them. # The firs

我浪费了早上的大部分时间没能解决这个简单的问题。使用python,我想解析如下所示的数据文件:

# This is an example comment line, it starts with a '#' character.
# There can be a variable number of comments between each data set.
# Comments "go with" the data set that comes after them.
# The first data set starts on the next line:
0.0 1.0
1.0 2.0
2.0 3.0
3.0 4.0

# Data sets are followed by variable amounts of white space.
# The second data set starts after this comment
5.0 6.0
6.0 7.0


# One more data set.
7.0 8.0
8.0 9.0
我想要的python代码将上述示例解析为三个“块”,将它们存储为列表的元素。单独的代码块本身可以存储为行列表,可以有注释行,也可以没有注释行。手动方式是这样做的:

#! /usr/bin/env python

# Read in data, seperate into rows_alldata
f=open("example")
rows = f.read().split('\n')
f.close()

# Do you haz teh codez?
datasets=[]
datasets.append(rows[0:8])
datasets.append(rows[9:13])
datasets.append(rows[15:18])
我正在寻找一个更通用的解决方案,支持可变数量和长度的数据集。我曾尝试过几次由非蟒蛇型环构成的灾难。我认为最好不要把我的问题和他们混在一起;这是工作而不是“家庭作业”

使用

输出:

[[['0.0', '1.0'], ['1.0', '2.0'], ['2.0', '3.0'], ['3.0', '4.0']],
 [['5.0', '6.0'], ['6.0', '7.0']],
 [['7.0', '8.0'], ['8.0', '9.0']]]

数据集总是以字符串的形式存储吗?数据是原始文本,但最后我会将其解析为浮动。你知道吗。。。再看一遍,我认为在我给出的示例中,基于数据集之间的空白块将其拆分是最容易的。这应该是f中的行的
。这不会使数据集分开@larsmans for循环中也少了一个冒号。哎呀,砰的一声,然后不得不去做一些工作,现在修好了。这正是我想要的。很高兴听到。如果您有numpy,我建议您考虑使用
np.loadtxt
来更轻松地解析浮动。考虑到
包含\u数据
实现,您可能希望使用通用换行符支持打开该文件mode@wim当前位置我已经发表了评论。具体如何处理注释和空行取决于OP的文件;可能有只包含空格等的行也需要解析掉。这也可以,尽管我认为它没有其他解决方案那么优雅。
datasets = [[]]
with open('/tmp/spam.txt') as f:
  for line in f:
    if line.startswith('#'):
      if datasets[-1] != []:
        # we are in a new block
        datasets.append([])
    else:
      stripped_line = line.strip()
      if stripped_line:
        datasets[-1].append(stripped_line)
from itertools import groupby

def contains_data(ln):
    # just an example; there are smarter ways to do this
    return ln[0] not in "#\n"

with open("example") as f:
    datasets = [[ln.split() for ln in group]
                for has_data, group in groupby(f, contains_data)
                if has_data]
import pprint

with open("test.txt") as fh:
    codes = []
    codeblock = []

    for line in fh:
        stripped_line = line.strip()

        if not stripped_line:
            continue

        if stripped_line.startswith("#"):
            if codeblock:
                codes.append(codeblock)
                codeblock = []

        else:
            codeblock.append(stripped_line.split(" "))

    if codeblock:
        codes.append(codeblock)

pprint.pprint(codes)
[[['0.0', '1.0'], ['1.0', '2.0'], ['2.0', '3.0'], ['3.0', '4.0']],
 [['5.0', '6.0'], ['6.0', '7.0']],
 [['7.0', '8.0'], ['8.0', '9.0']]]