python - 如何获取指定字符串之前的五个字符串?
问题描述
接下来是我的任务。我有一个文件。我需要从文件中获取确切的字符串加上指定字符串之前的五个字符串。我试图这样做:
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 = [])与从文件中获得的真实字符串连接起来,并分别获得五个字符串。
提前感谢您的帮助。
解决方案
您可以使用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']
推荐阅读
- angular - *ngIf 在 Object 被填充后不更新
- javascript - 如何在JS中用图像替换div内容
- java - OpenCSV 从文件中读取奇怪的文本
- javascript - 在 startkey 数组中为视图传递空键
- wordpress - wordpress - 在whatsapp链接中共享私人内容未正确显示
- html - 如何让语义 UI 段正确适应页面宽度
- php - 在 laravel 控制器中进行 Foreach,但只得到单个数据
- machine-learning - 机器学习模型的行业生产参数
- python - Keras model & Tensorflow Estimator - 模型响应处理
- .net - pdf格式在itext7中为空