简体   繁体   English

python解析文本文件中的条件多行

[英]python parse conditional multiple lines in text file

I would like to parse a text file, but with multiple conditions:我想解析一个文本文件,但有多个条件:

Input:输入:

something<br />
something <br />
something<br />
Modifications made by xy (xy) on 2019/12/10 10:40:23<br />
location: A --> B<br />
something<br />
something<br />
something<br />
Modifications made by xz (xz) on 2020/01/17 11:11:59<br />
analyzer: C --> D<br />
analyzer: B --> D<br />
analyzer: G --> D<br />
location: E --> F<br />
something<br />
something<br />
something

Task: I need to find the "location: x --> y" and date before the location.任务:我需要在位置之前找到“位置:x --> y”和日期。 The txt file can contains unknown number of location change. txt 文件可以包含未知数量的位置更改。

Required Output:所需输出:

2019/12/10 10:40:23, location: A --> B
2020/01/17 11:11:59, location: E --> F

I tried some code eg.:我尝试了一些代码,例如:

with open('log.txt', 'r') as searchfile:
    for line in searchfile:
        if 'location' in line:
            print (line)

but only find the locations and I don't know how to find the dates for them.但只能找到位置,我不知道如何找到它们的日期。

Thank you in advance.先感谢您。

Just keep track of corresponding times and locations as such:只需跟踪相应的时间和地点:

with open('log.txt', 'r') as searchfile:
    time = None
    for line in searchfile:
        if line.startswith('Modifications made by'):
            time = line.split('on')[-1].strip()
        elif line.startswith('location') and time is not None:
            print(f'{time}, {line}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM