我是 Python 的新手。我经常使用 Perl,听说 Python 通常更擅长解析文本,所以我想试一试,但我想不出最简单的方法(有关信息,我已经用 Perl 做过,但它花了我几个,缓慢而丑陋的循环):
我想读取一个大文件并提取以相同模式开头的两行之间的文本 block ,例如:
!NAME: "N0", DESCR: "Netnt Etrnet"
!NAME: "cp0", DESCR: "Cle R0"
!NAME: "slt R1", DESCR: "RSt"
>>!NAME: "moe R1", DESCR: "ASessor 1,bps"
>>!PID: A9-55
>>!VID: G0984981
>>!SN: SEDGH25443N51E
!NAME: "SDFGSDFG: FGT/0", DESCR: "VFDFGX1"
!NAME: "JQFHF1", DESCR: "VNQDF2"
当然“>>”不是文本文件的一部分,它只是为了显示我想要检索的行。
所以回顾一下:我想打印所有 block (文件中有更多 block ),其中 block 的第一行以“!NAME”开头,并且在下一个“!NAME”之前有其他行。
我不关心连续有两个“!NAME:”的 block 。
这只是第一步,稍后我将尝试检索此 block 的值以创建散列(或字典或任何与 Python 中的散列等效的内容)。但我已经卡在了第一步,所以我正在寻求帮助哈哈。
谢谢!
with open("in.txt") as f:
prev = ""
for line in f:
if not line.startswith("!NAME:"):
print(prev.rstrip())
print(line.rstrip())
for line in f:
if line.startswith("!NAME:"):
prev = line
break
print(line.rstrip())
prev = line
prev = line
如果你想存储每个部分,你可以使用字典:
from itertools import count
from collections import defaultdict
cn = count()
sections = defaultdict(str)
with open("log.txt") as f:
prev = ""
for line in f:
if not line.startswith("!NAME:"):
key = next(cn)
sections[key] += prev
sections[key] += line
for line in f:
if line.startswith("!NAME:"):
break
sections[key] += line
prev = line
prev = line
print(d)
defaultdict(<class 'str'>, {0: '!NAME: "moe R1", DESCR: "ASessor 1,bps"\n!PID: A9-55\n!VID: G0984981\n!SN: SEDGH25443N51E\n'})
为确保您只找到前面有 !Name 的部分,请确保前一行以 !Name 开头:
with open("log.txt") as f:
prev = ""
for line in f:
if not line.startswith("!NAME:") and prev.startswith("!NAME:"):
key = next(cn)
sections[key] += prev
sections[key] += line
for line in f:
if line.startswith("!NAME:"):
break
sections[key] += line
prev = line
prev = line