搜索文本文件并在Python中打印相关行? [英] Search a text file and print related lines in Python?

查看:192
本文介绍了搜索文本文件并在Python中打印相关行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

print l,中的逗号可防止在输出中出现多余的空格;尾随的打印语句将结果划分为不同的行.

The comma in print l, prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.

或更妙的是(从马克·兰森偷走):

Or better yet (stealing back from 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中打印相关行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆