获取文件Python中某些短语的行号

Zac*_*own 46 python file

我需要在文本文件中获取短语的行号.这句话可能是:

the dog barked
Run Code Online (Sandbox Code Playgroud)

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

我在Windows XP上使用Python 2.6


这就是我所拥有的:

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

这不是作业,它是我正在进行的项目的一部分.我甚至不知道如何获得行号.

Sac*_*cha 89

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
Run Code Online (Sandbox Code Playgroud)

  • 感谢您发布*正确的方式(tm)*来做(好吧,除了行计数从0开始 - 对于程序员来说是好的,但对于非技术人员来说可能不是这样).+1 (3认同)
  • 在python 2.6及更高版本中,我认为,`enumerate()`接受一个数字的参数来开始计数,例如`enumerate(myFile,1)`. (2认同)
  • 您可以检查这篇文章以在特定行打开文件:http://stackoverflow.com/questions/620367/python-how-to-jump-to-a-pspecial-line-in-a-huge-text -文件 (2认同)

dr *_*bob 7

f = open('some_file.txt','r')
line_num = 0
search_phrase = "the dog barked"
for line in f.readlines():
    line_num += 1
    if line.find(search_phrase) >= 0:
        print line_num
Run Code Online (Sandbox Code Playgroud)

编辑1.5年后(看到它得到另一个upvote):我将离开这个原样; 但如果我今天写作会写一些更接近Ash/suzanshakya的解决方案:

def line_num_for_phrase_in_file(phrase='the dog barked', filename='file.txt')
    with open(filename,'r') as f:
        for (i, line) in enumerate(f):
            if phrase in line:
                return i
    return -1
Run Code Online (Sandbox Code Playgroud)
  • 使用with打开文件是Python的成语-它确保该文件将在使用该文件的块结束正常关闭.
  • 使用文件迭代for line in f比使用文件要好得多for line in f.readlines().前者是pythonic(例如,如果f是任何泛型可迭代的话可以工作;不一定是实现的文件对象readlines),并且更高效地f.readlines()创建一个列表,其中整个文件在内存中然后迭代它.*if search_phrase in line比更Python if line.find(search_phrase) >= 0,因为它并不需要line实现find,读取更容易,看看有什么打算,并且不容易搞砸了(例如,if line.find(search_phrase)if line.find(search_phrase) > 0作为find返回第一个匹配的指数既不会为所有情况或-1).
  • 它的简单/清洁剂在包装一个迭代的项目enumerate一样for i, line in enumerate(f),而不是初始化line_num = 0循环之前,然后在循环手动递增.(虽然可以说,对于不熟悉的人来说,这更难以阅读enumerate.)

请参阅pythonista之类的代码


suz*_*kya 5

def get_line_number(phrase, file_name):
    with open(file_name) as f:
        for i, line in enumerate(f, 1):
            if phrase in line:
                return i
Run Code Online (Sandbox Code Playgroud)