我有以下示例文本,需要根据单词“ALL Banks Report”将所有文本行传递给元组/列表..原始文本如下
%Bank PARSED MESSAGE FILE
%VERSION : PIL 98.7
%nex MODULE : SIL 98
2018 Jan 31 16:44:53.050 ALL Banks Report SBI
name id ID = 0, ID = 58
Freq = 180
conserved NEXT:
message c1 : ABC1 :
{
XYZ2
}
2018 Jan 31 16:44:43.050 ALL Banks Report HDFC
conserved LATE:
World ::=
{
Asia c1 : EastAsia :
{
India
}
}
...喜欢这么多的礼物 我想基于单词“ALL Banks Report”传递元组/列表/数组,以便在列表[0]中进行以下操作
2018 Jan 31 16:44:53.050 ALL Banks Report SBI
name id ID = 0, ID = 58
Freq = 180
conserved NEXT:
message c1 : ABC1 :
{
XYZ2
}
并在列表[1]中,其余部分如下所示
2018 Jan 31 16:44:43.050 ALL Banks Report HDFC
conserved LATE:
World ::=
{
Asia c1 : EastAsia :
{
India
}
}
答案 0 :(得分:1)
IMO,这里使用pyparsing没有特别的优势。使用老式算法很容易处理这个文件。
2018 Jan 31 16:44:53.050 ALL Banks Report SBI
name id ID = 0, ID = 58
Freq = 180
conserved NEXT:
message c1 : ABC1 :
{
XYZ2
}
2018 Jan 31 16:44:43.050 ALL Banks Report HDFC
conserved LATE:
World ::=
{
Asia c1 : EastAsia :
{
India
}
}
输出:
list
顺便说一下,我避免使用{{1}}作为标识符,因为它是Python关键字。
答案 1 :(得分:1)
我是itertools.groupby
的忠实粉丝,这是一种非传统的方式来使用它来查找您的银行组:
from itertools import groupby
is_header = lambda s: "ALL Banks Report" in s
lines = sample.splitlines()
# call groupby to group lines by whether or not the line is a header or not
group_iter = groupby(lines, key=is_header)
# skip over leading group of non-header lines if the first line is not a header
if not is_header(lines[0]):
next(group_iter)
groups = []
while True:
head_lines = next(group_iter, None)
# no more lines? we're done
if head_lines is None:
break
# extract header lines, which is required before trying to advance the groupby iter
head_lines = list(head_lines[1])
# if there were multiple header lines in a row, with no bodies, create group items for them
while len(head_lines) > 1:
groups.append([head_lines.pop(0)])
# get next set of lines which are NOT header lines
body_lines = next(group_iter, (None, []))
# extract body lines, which is required before trying to advance the groupby iter
body_lines = list(body_lines[1])
# we've found a head line and a body, save it as a single list
groups.append(head_lines + body_lines)
# what did we get?
for group in groups:
print('--------------')
print('\n'.join(group))
print('')
使用您的数据集:
--------------
2018 Jan 31 16:44:53.050 ALL Banks Report SBI
name id ID = 0, ID = 58
Freq = 180
conserved NEXT:
message c1 : ABC1 :
{
XYZ2
}
--------------
2018 Jan 31 16:44:43.050 ALL Banks Report HDFC
conserved LATE:
World ::=
{
Asia c1 : EastAsia :
{
India
}
}