python 解析文本文件中的条件多行
python parse conditional multiple lines in text file
我想解析一个文本文件,但有多个条件:
输入:
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
任务:
我需要在位置之前找到 "location: 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)
但只找到地点,我不知道如何找到它们的日期。
提前致谢。
只需记录相应的时间和地点即可:
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}')
我想解析一个文本文件,但有多个条件:
输入:
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
任务: 我需要在位置之前找到 "location: 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)
但只找到地点,我不知道如何找到它们的日期。
提前致谢。
只需记录相应的时间和地点即可:
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}')