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

2024-09-28 21:04:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要得到文本文件中短语的行号。短语可以是:

the dog barked

我需要打开文件,搜索它的短语并打印行号。

我在WindowsXP上使用Python2.6


这就是我所拥有的:

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

这不是家庭作业,是我正在做的一个项目的一部分。我一点也不知道怎么得到电话号码。


Tags: 文件theintxtreadifitopen
3条回答
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
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

1.5年后编辑(在看到它得到另一张赞成票之后):我现在就不写了;但是如果我今天写的话,我会写一些更接近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
  • 使用with打开文件是pythonic的习惯用法——它确保在使用文件的块结束时正确关闭文件。
  • 使用for line in f遍历文件比for line in f.readlines()好多了。前者是pythonic(例如,如果f是任何泛型的iterable都可以工作;不一定是实现readlines的文件对象),更有效的是f.readlines()创建一个包含整个文件的列表,然后遍历它。*if search_phrase in lineif line.find(search_phrase) >= 0更像Python,因为它不需要line来实现find,读起来更容易看到目的,也不容易出错(例如,if line.find(search_phrase)if line.find(search_phrase) > 0这两种方法都不适用于所有情况,因为find返回第一个匹配项或-1的索引。
  • 它比在循环之前初始化循环中的line_num = 0然后在循环中手动递增更简单/更干净。(尽管可以说,对于不熟悉enumerate的人来说,这更难阅读。)

code like pythonista

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

相关问题 更多 >