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

最佳答案

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

关于python - 搜索文本文件并在Python中打印相关行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4785244/

10-10 13:17