在 Python 中搜索文本文件并打印相关行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4785244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search a text file and print related lines in Python?
提问by Noah R
How do I search a text file for a key-phrase or keyword and then print the line that key-phrase or keyword is in?
如何在文本文件中搜索关键短语或关键字,然后打印关键短语或关键字所在的行?
采纳答案by senderle
searchfile = open("file.txt", "r")
for line in searchfile:
if "searchphrase" in line: print line
searchfile.close()
To print out multiple lines (in a simple way)
打印多行(以简单的方式)
f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
if "searchphrase" in line:
for l in searchlines[i:i+3]: print l,
print
The comma in print l,prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.
逗号 inprint l,防止输出中出现多余的空格;尾随的打印语句将结果划分为不同的行。
Or better yet (stealing back from Mark Ransom):
或者更好(从 Mark Ransom 那里偷回来):
with open("file.txt", "r") as f:
searchlines = f.readlines()
for i, line in enumerate(searchlines):
if "searchphrase" in line:
for l in searchlines[i:i+3]: print l,
print
回答by Mark Ransom
回答by bill
Note the potential for an out-of-range index with "i+3". You could do something like:
请注意“i+3”超出范围索引的可能性。你可以这样做:
with open("file.txt", "r") as f:
searchlines = f.readlines()
j=len(searchlines)-1
for i, line in enumerate(searchlines):
if "searchphrase" in line:
k=min(i+3,j)
for l in searchlines[i:k]: print l,
print
Edit: maybe not necessary. I just tested some examples. x[y] will give errors if y is out of range, but x[y:z] doesn't seem to give errors for out of range values of y and z.
编辑:也许没有必要。我只是测试了一些例子。如果 y 超出范围,x[y] 将给出错误,但 x[y:z] 似乎不会为超出范围的 y 和 z 值给出错误。

