获取Python文件中特定短语的行号

2024-06-28 20:10:32 发布

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

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

the dog barked

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

我正在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"

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


Tags: 文件thetxtreadifwindowsitopen
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
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
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更具pythonic,因为它不需要line来实现find,更容易阅读以查看意图,也不容易出错(例如if line.find(search_phrase)if line.find(search_phrase) > 0这两种方法都不适用于所有情况,因为find返回第一个匹配的索引或-1)
  • 与在循环之前初始化line_num = 0然后在循环中手动递增相比,在类似enumeratefor i, line in enumerate(f)中包装迭代项更简单/更干净。(尽管有争议,但对于不熟悉enumerate的人来说,这更难理解。)

code like pythonista

相关问题 更多 >