首页 > 解决方案 > 如何获取指定字符串之前的五个字符串?

问题描述

接下来是我的任务。我有一个文件。我需要从文件中获取确切的字符串加上指定字符串之前的五个字符串。我试图这样做:

import re
import glob
index = 0
ArrayListStringIndex = []
for filename in glob.glob('syslog'):
    file = open ((filename), "r")
    for SearchPrase in file:
        if re.search ((": New USB device found"), SearchPrase):
            ArrayListStringIndex.append(index)
        index = index + 1 

但是我不知道如何将我从文件中获得的字符串数列表(ArrayListStringIndex = [])与从文件中获得的真实字符串连接起来,并分别获得五个字符串。

提前感谢您的帮助。

标签: python

解决方案


您可以使用deque长度为 5 的 a 作为缓存。您只需在迭代时附加每个字符串,双端队列会为您限制大小,根据需要从前面弹出项目。例如:

from collections import deque

strings = (f'a{n}' for n in range(20))  # Generator to act as a dummy file
d = deque([], 5)
target = '8'

for s in strings:
    if target in s:
        print(s, list(d))
    d.append(s)

输出:

a8 ['a3', 'a4', 'a5', 'a6', 'a7']
a18 ['a13', 'a14', 'a15', 'a16', 'a17']

这也可以毫不费力地处理早期事件,例如target = '3'

a3 ['a0', 'a1', 'a2']
a13 ['a8', 'a9', 'a10', 'a11', 'a12']

推荐阅读