我是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个模块标签。你知道吗
好的,这里有一个例子给你,所以你可以更具体的你需要什么。你知道吗
这是您的
huge_file.txt
示例:还有一个脚本
read_prev_lines.py
:相关问题 更多 >
编程相关推荐