如何读取Python中的前一行相对于日志文件中的搜索?

问题描述 投票:0回答:1

我是Python的新手,所以只是用它来尝试。 我有一个巨大的文件,在搜索一个搜索短语后,我应该返回n行并获取文本的开头,开始标记。之后开始从该位置读取。

短语可以多次出现。并且有多个开始标记。请查找示例文件,如下所示:

<module>
hi
flowers
<name>xxx</name>
<age>46</age>
</module>
<module>
<place>yyyy</place>
<name>janiiiii</janii>
</module>

假设搜索是,我需要在搜索后返回到该行。 &之间的界限会有所不同,它们不是静态的。所以一旦找到名称,我需要回到模块行并开始阅读它。

请找到以下代码:

from itertools import islice
lastiterline=none
line_num=0
search_phrase="Janiii"
with open ('c:\sample.txt',"rb+") as f:
      for line in f:
          line_num+=1
     line=line.strip()
        if line.startswith("<module>"):
           lastiterline=line
           linec=line_num
        elif line find(search_phrase)>=0:
             if lastiterline:
             print line
             print linec

这有助于我获取与搜索到的单词对应的模块的行号。但是我无法移回指针以开始从模块再次读取行。会有多个搜索短语,所以每当我需要回到那条线而不会破坏主要内容时,它会读取整个巨大的文件。

例如:可能有100个模块标签,在里面我可能有10个我想要的搜索短语,所以我只需要那些10个模块标签。

python python-2.7 logfile readlines
1个回答
0
投票

好的,这里有一个例子,所以你可以更具体地了解你的需求。

这是你的huge_file.txt的样本:

wgoi jowijg
<start tag>
wfejoije jfie
fwjoejo
THE PHRASE
jwieo
<end tag>
wjefoiw wgworjg
<start tag>
wjgoirg 
<end tag>
<start tag>
wfejoije jfie
fwjoejo
woeoj
jwieo
THE PHRASE
<end tag>

和脚本read_prev_lines.py

hugefile = open("huge_file.txt", "r")
hugefile = hugefile.readlines()

start_locations = []
current_block = -1
for idx, line in enumerate(hugefile):
  if "<start tag>" in line:
    start_locations.append({"start": idx})
    current_block += 1
  if "THE PHRASE" in line:
    start_locations[current_block]["phr"] = idx
  if "<end tag>" in line:
    start_locations[current_block]["end"] = idx

#for i in phrase_locations:
for idx in range(len(start_locations)):
  if "phr" in start_locations[idx].keys():
    print("Found THE PHRASE after %d start tag(s), at line %d:" % (idx, start_locations[idx]["phr"]))
    print("Here is the whole block that contains the phrase:")
    print(hugefile[start_locations[idx]["start"]: start_locations[idx]["end"]+1])
© www.soinside.com 2019 - 2024. All rights reserved.