如何读取Python中与日志文件中的搜索相关的前几行?

2024-09-24 04:19:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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

这有助于我获得与单词对应的模块行号搜索过了,但是我无法向后移动指针以重新开始从模块中读取行。将有多个搜索短语,所以每次我需要回到那一行,而不打破主for,它读取整个巨大的文件。你知道吗

例如:可能有100个模块标签,里面我可能有10个搜索短语,我想要,所以我只需要这10个模块标签。你知道吗


Tags: 模块文件name标记foragesearchif
1条回答
网友
1楼 · 发布于 2024-09-24 04:19:38

好的,这里有一个例子给你,所以你可以更具体的你需要什么。你知道吗

这是您的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])

相关问题 更多 >