提取文本中字符串之间的信息

2024-09-30 01:29:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据文件结构如下:

handle:trial1

key_left:3172

key_up:

xcoords:12,12,12,15........

ycoords:200,200,206,210,210......

t:20,140,270,390.....

goalx:2

goaly:12

fractal:images/file.png

seen:true

pauseTimes:

fractal:images/file2.png

seen:False

pauseTimes:

...
...

我只想提取goaly行之后直到pauseTimes行的信息。如果我知道所有试验的goaly值,我可以指定那一行并提取goaly:pauseTimes之间的数据,但是我不会提前知道任何goaly的值是什么,因为它们是动态生成的。你知道吗

如何使用字符串"goaly"标识该行,然后提取所有后续行直到pauseTimes行?你知道吗


Tags: keypng数据文件结构lefthandleimagesup
2条回答
extracting = False
with open('path/to/file') as f:
    for line in f:
        if line.startswith('goaly:'):
            extracting = True
        if extracting:
            # I'm not really sure how you want to receive this
            # data, but that's what would go here....
        if line.startswith('pauseTimes:'):
            extracting = False

不管是否关心行,都可以使用状态变量进行循环和跟踪。我喜欢用生成器跟踪这样的解析状态,使其与处理代码分离。例如,以下是生成器:

def parse(infile):
    returning = False
    trial = None
    for line in infile:
        line = line.rstrip()
        if not line:
            continue

        if line.startswith('handle:'):
            trial = line[len('handle:'):]

        if line.startswith('goaly:'):
            returning = True
        elif line.startswith('pauseTimes:'):
            returning = False

        if returning:
            yield trial, line

下面是您如何使用它:

for trial, line in parse(open('test.txt', 'r')):
    print(trial, line)

还有一个额外的功能,就是跟踪你正在进行的审判。你知道吗

相关问题 更多 >

    热门问题