[英]Copy few lines before and after the match string in python
I am new to python and trying to write a script for copying 5 lines before and 5 after the matching string is found 我是python的新手,尝试编写一个脚本,在找到匹配的字符串之前复制5行,然后复制5行
import re
text_file = open(input("Input-file name : ") , "r")
fi = text_file.readlines()
test = re.compile(r'matching character')
for i in range (len(fi)):
if test.search(fi[i]):
print(fi[max(0, i-5)])
print(fi[max(0, i-4)])
print(fi[max(0, i-3)])
print(fi[max(0, i-2)])
print(fi[max(0, i-1)])
print(fi[max(0, i-0)])
print(fi[max(0, i+1)])
print(fi[max(0, i+2)])
print(fi[max(0, i+3)])
print(fi[max(0, i+4)])
Is there a better way than adding multiple print statements to get the output in one command. 有没有比添加多个print语句在一个命令中获得输出更好的方法。
Assuming that the matched line is included in the 5 lines "after", then: 假定匹配的行包含在“之后”的5行中,则:
block = fi[max(0, i - 5): min(len(fi), i + 5)]
will give you a list of the lines. 将为您提供行列表。 To print the list as one block, you can do:
要将列表打印为一个块,您可以执行以下操作:
print(''.join(block))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.