【问题标题】:python parse conditional multiple lines in text filepython解析文本文件中的条件多行
【发布时间】:2020-05-19 07:55:36
【问题描述】:

我想解析一个文本文件,但有多个条件:

输入:

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

任务: 我需要在位置之前找到“位置:x --> y”和日期。 txt文件可以包含未知数量的位置变化。

所需输出:

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

我尝试了一些代码,例如:

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

但只找到地点,我不知道如何找到他们的日期。

提前谢谢你。

【问题讨论】:

    标签: python regex python-3.x text-parsing


    【解决方案1】:

    只需跟踪相应的时间和地点即可:

    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}')
    

    【讨论】:

    • 谢谢@Sam。一修改。而不是 [1],[-1] 显示日期,但它完美地工作。
    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多