获取文件Python中特定短语的行号 [英] Get Line Number of certain phrase in file Python

查看:96
本文介绍了获取文件Python中特定短语的行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取文本文件中短语的行号.该短语可能是:

I need to get the line number of a phrase in a text file. The phrase could be:

the dog barked

我需要打开文件,搜索该短语并打印行号.

I need to open the file, search it for that phrase and print the line number.

我在Windows XP上使用Python 2.6

I'm using Python 2.6 on Windows XP

这就是我所拥有的:

o = open("C:/file.txt")
j = o.read()
if "the dog barked" in j:
     print "Found It"
else:
     print "Couldn't Find It"

这不是家庭作业,它是我正在从事的项目的一部分.我什至不知道如何获取行号.

This is not homework, it is part of a project I am working on. I don't even have a clue how to get the line number.

推荐答案

lookup = 'the dog barked'

with open(filename) as myFile:
    for num, line in enumerate(myFile, 1):
        if lookup in line:
            print 'found at line:', num

这篇关于获取文件Python中特定短语的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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