如何在指定字符串之前获取五个字符串?

2024-10-02 10:20:24 发布

您现在位置: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=[])与实际字符串连接起来,之前分别得到了五个Sting

提前谢谢你的帮助


Tags: 字符串inimportreforindexif档案
3条回答
>>> message = "Always split your problem up in different parts, I'll try to purely answer on the title."
>>> words = message.split(" ")  # split the message in words
>>> index = words.index("different")  # find the index of your specific word
>>> for i in range(index - 5, index):  # iterate over the previous 5 words
...     if i > 0:
...             print(words[i])
... 
split
your
problem
up
in

你可以试试

import re
import glob

arrayListStringIndex = []
for filename in glob.glob('syslog'):
    file = open((filename), "r")
    file_lines = file.readlines()
    for index, searchPrase in enumerate(file_lines):
        if re.search ((": New USB device found"), searchPrase):
            arrayListStringIndex.append(index)
    for i in arrayListStringIndex:
        print(file_lines[i-5 if i > 5 else 0:i if i > 0 else 1])

这将打印所有精确的匹配行,前面有5行

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

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']

相关问题 更多 >

    热门问题