[英]How to print the last occurence of a string plus the following N lines
I'm trying to write a file output parser and am having trouble with coming up with a solution to how to print the last occurrence of a string + the following N number of lines. 我正在尝试编写一个文件输出解析器,并且遇到了如何打印最后一次出现的字符串+以下N行数的解决方案。 The output files are generally less than 2 MB so I shouldn't have any issues reading the file to memory, but if there is a more elegant solution that would be nice for learning sake.
输出文件通常小于2 MB,所以我不应该有任何问题将文件读取到内存,但如果有一个更优雅的解决方案,这将是一个很好的学习。
I have tried saving the lines into a list and then printing out the last occurrences, but it splits the lines into words so the lists end up being to hard to work with. 我已经尝试将行保存到列表中,然后打印出最后一次出现,但它将行拆分为单词,因此列表最终难以使用。 I also have the program reading the total number of lines needed to be printed earlier if there is another solution than what I have tried.
如果还有其他解决方案,我还有程序读取需要打印的总行数。
def coord():
stdOrn = 'Standard orientation'
coord = {}
found = False
with open(name, 'r') as text_file:
for line in text_file:
if stdOrn in line:
found = True
elif 'Rotational constants (GHZ)' in line:
found = False
elif found:
coord = line
outFile.write(coord)
You can load it as a string, get the index of the last appearance with .rfind()
and then do a string slice from the last index. 您可以将其作为字符串加载,使用
.rfind()
获取最后一次出现的索引,然后从最后一个索引执行字符串切片。
stdOrn = 'Standard orientation'
found = False
with open(name, 'r') as text_file:
file_contents = text_file.read()
last_appearance = file_contents.rfind(std0rn)
following_n_lines = file_contents[last_appearance:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.