【问题标题】:python - get target line in a file etc. then get a specific previous line?python - 在文件等中获取目标行然后获取特定的前一行?
【发布时间】:2014-10-23 16:40:29
【问题描述】:

我需要在某些输出中找到某一行。我可以这样做,但是在找到输出的正确部分后,我需要在该部分之前提取某些行。

for i, line in enumerate(lines):
 target = str(self.ma3) # set target string
 if target in line:
  print i, line     # this gets the correct line, I can stick it in a variable and do stuff with it
  i = i - 4         # now I want the line 4 lines before the initial target line
  print lines[i]    # doesn't work, gives error: TypeError: 'generator' object has no attribute '__getitem__'

如果有人知道如何做到这一点,我们将不胜感激!

【问题讨论】:

  • 你是如何创建线条的?您也可以只使用lines[i-4]
  • lines = 我调用的进程的终端输出。我尝试了你的建议,但得到了同样的错误。
  • 我并不是说它会起作用,我的意思是在下面的答案中添加你不需要使用i = i - 4 你可以使用lines[i-4]

标签: python string enumerate readlines


【解决方案1】:

同意列表(行)答案。最简单的解决方案。

但是,如果您的输入文件太大并且您想坚持使用生成器,那么 collections.deque 应该可以保留最后 4 行以防万一。旧的行将被丢弃。

from collections import deque

mybuffer = deque(maxlen=4)

for i, line in enumerate(lines):
   mybuffer.append(line)
   #...some more of your code...
   if target in line:
       line_4_lines_before = mybuffer[0]
       line_3_lines_before = mybuffer[1]

【讨论】:

    【解决方案2】:

    您需要使用列表来进行随机访问:

    lines = list(lines)
    
    # your code
    

    生成器一次只为您提供一个项目,并且没有“索引”的概念,这与列表不同。

    或者,如果您的文件非常大并且将所有行放入一个列表中的成本太高,您可以一次从生成器中提取 4 个项目。这样,如果您找到它,您就可以访问目标行之前的四行。您必须做一些簿记以确保您不会跳过任何行。

    【讨论】:

      猜你喜欢
      • 2013-01-22
      • 2022-12-24
      • 1970-01-01
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      • 2017-11-13
      • 2014-11-24
      • 1970-01-01
      相关资源
      最近更新 更多