我正在处理由报告软件生成的大型(约 5000 行)文本文件。这些文件每页有多个标题行,并且通篇有许多空行。我想出了一种过滤掉不需要的数据的方法,但我想知道这是否是最好的方法。我有这个用于过滤列表的函数,它基本上是遍历列表并通过每次删除其中一个过滤行来减少它。
def process_block(b):
b1 = [line for line in b if not line.startswith('100 V')]
b2 = [line for line in b1 if not line.startswith('300 V')]
b3 = [line for line in b2 if not line.startswith('400 V')]
b4 = [line for line in b3 if not line.startswith('AR00000')]
b5 = [line for line in b4 if not line.startswith('734 - C')]
b6 = [line for line in b5 if not line.lstrip().startswith('TXN DAT')]
b7 = [line for line in b6 if not line.startswith(' ACCO')]
b8 = [line for line in b7 if not line.rstrip() == '']
return b8
我觉得我的传球次数超出了必要。有没有更好的方法来完成此过滤?
请您参考如下方法:
您绝对可以一次完成。
def process_block(b)
return [line for line in b if
not line.startswith(
('100 V', '300 V', '400 V', 'AR00000', '734 - C', ' ACCO')
)
and not line.lstrip().startswith('TXN DAT')
and not line.rstrip() == '']
