【发布时间】:2021-03-20 06:47:27
【问题描述】:
我有一个文本文件,我需要从中提取某些数据。我需要的数据将出现在以“No.”开头的标题下。所以我知道在搜索文件时要查找什么,并且可以拆分和打印每个标题。但是,我想提取以“否”开头的数据的下一行的数据。我也不能使用正则表达式。我怎样才能做到这一点?我能够使用下面的代码成功地找到文件中的每个标题,但如前所述,我想获得下一行。
with open(path, 'r') as f:
for line in f:
if KEYWORD in line:
data = line.split()
print(data)
打印出标题:
['No.', 'Time', 'Source', 'Destination', 'Protocol', 'Length', 'Info']
['No.', 'Time', 'Source', 'Destination', 'Protocol', 'Length', 'Info']
['No.', 'Time', 'Source', 'Destination', 'Protocol', 'Length', 'Info']
['No.', 'Time', 'Source', 'Destination', 'Protocol', 'Length', 'Info']
['No.', 'Time', 'Source', 'Destination', 'Protocol', 'Length', 'Info']
['No.', 'Time', 'Source', 'Destination', 'Protocol', 'Length', 'Info']
['No.', 'Time', 'Source', 'Destination', 'Protocol', 'Length', 'Info']
文本文件示例
Internet Protocol Version 4, Src: 192.168.1.180, Dst: 239.255.255.250
0100 .... = Version: 4
.... 0101 = Header Length: 20 bytes (5)
Differentiated Services Field: 0x00 (DSCP: CS0, ECN: Not-ECT)
Total Length: 358
Identification: 0xfe2a (65066)
Flags: 0x4000, Don't fragment
Time to live: 4
Protocol: UDP (17)
Header checksum: 0xc505 [validation disabled]
[Header checksum status: Unverified]
Source: 192.168.1.180
Destination: 239.255.255.250
User Datagram Protocol, Src Port: 35064, Dst Port: 1900
Simple Service Discovery Protocol
No. Time Source Destination Protocol Length Info
2 0.307821 192.168.1.180 239.255.255.250 SSDP 422 NOTIFY * HTTP/1.1
【问题讨论】: