搜索文本文件并在Python中打印相关的行?

时间:2011-01-24 17:49:24

标签: python file search

如何在文本文件中搜索关键词或关键词,然后打印关键词或关键词所在的行?

3 个答案:

答案 0 :(得分:52)

searchfile = open("file.txt", "r")
for line in searchfile:
    if "searchphrase" in line: print line
searchfile.close()

打印多行(以简单的方式)

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

print l,中的逗号可防止额外空格出现在输出中;尾随打印语句划分不同行的结果。

或者更好(从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

答案 1 :(得分:19)

with open('file.txt', 'r') as searchfile:
    for line in searchfile:
        if 'searchphrase' in line:
            print line

向我公然抄袭的senderle道歉。

答案 2 :(得分:2)

注意“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

编辑:也许没必要。我刚刚测试了一些例子。如果y超出范围,x [y]将给出错误,但x [y:z]似乎不会给y和z的超出范围值带来错误。