获取文件 Python 中某个短语的行号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3961265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Line Number of certain phrase in file Python
提问by Zac Brown
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.
我需要打开文件,搜索该短语并打印行号。
I'm using Python 2.6 on Windows XP
我在 Windows XP 上使用 Python 2.6
This Is What I Have:
这就是我所拥有的:
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.
这不是家庭作业,它是我正在进行的项目的一部分。我什至不知道如何获得行号。
采纳答案by Sacha
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
回答by slezica
Open your file, and then do something like...
打开您的文件,然后执行类似...
for line in f:
nlines += 1
if (line.find(phrase) >= 0):
print "Its here.", nlines
There are numerous ways of reading lines from files in Python, but the for line in ftechnique is more efficient than most.
在 Python 中有多种从文件中读取行的for line in f方法,但该技术比大多数方法更有效。
回答by dr jimbob
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
EDIT 1.5 years later (after seeing it get another upvote): I'm leaving this as is; but if I was writing today would write something closer to Ash/suzanshakya's solution:
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
- Using
withto open files is the pythonic idiom -- it ensures the file will be properly closed when the block using the file ends. - Iterating through a file using
for line in fis much better thanfor line in f.readlines(). The former is pythonic (e.g., would work iffis any generic iterable; not necessarily a file object that implementsreadlines), and more efficientf.readlines()creates an list with the entire file in memory and then iterates through it. *if search_phrase in lineis more pythonic thanif line.find(search_phrase) >= 0, as it doesn't requirelineto implementfind, reads more easily to see what's intended, and isn't easily screwed up (e.g.,if line.find(search_phrase)andif line.find(search_phrase) > 0both will not work for all cases as find returns the index of the first match or -1). - Its simpler/cleaner to wrap an iterated item in
enumeratelikefor i, line in enumerate(f)than to initializeline_num = 0before the loop and then manually increment in the loop. (Though arguably, this is more difficult to read for people unfamiliar withenumerate.)
- 使用
with打开文件是pythonic的习惯用法——它确保在使用文件的块结束时文件将被正确关闭。 - 遍历文件使用
for line in f比for line in f.readlines(). 前者是pythonic(例如,如果f是任何通用的可迭代的,就可以工作;不一定是实现 的文件对象readlines),并且更有效地f.readlines()创建一个包含内存中整个文件的列表,然后遍历它。*if search_phrase in line比更Pythonif line.find(search_phrase) >= 0,因为它并不需要line实现find,读取更容易,看看有什么打算,并且不容易搞砸了(例如,if line.find(search_phrase)和if line.find(search_phrase) > 0都为所有案件的发现回报将无法正常工作的第一场比赛的索引或-1)。 - 它的简单/清洁剂在包装一个迭代的项目
enumerate一样for i, line in enumerate(f),而不是初始化line_num = 0循环之前,然后在循环手动递增。(虽然可以说,这对于不熟悉enumerate.的人来说更难阅读。)
回答by suzanshakya
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
回答by ghostdog74
for n,line in enumerate(open("file")):
if "pattern" in line: print n+1
回答by M. kavin babu
listStr = open("file_name","mode")
if "search element" in listStr:
print listStr.index("search element") # This will gives you the line number
回答by Onkar Raut
Here's what I've found to work:
这是我发现的工作:
f_rd = open(path, 'r')
file_lines = f_rd.readlines()
f_rd.close()
matches = [line for line in file_lines if "chars of Interest" in line]
index = file_lines.index(matches[0])
回答by Amarjeet Ranasingh
suzanshakya, I'm actually modifying your code, I think this will simplify the code, but make sure before running the code the file must be in the same directory of the console otherwise you'll get error.
suzanshakya,我实际上是在修改你的代码,我认为这会简化代码,但在运行代码之前确保文件必须在控制台的同一目录中,否则你会得到错误。
lookup="The_String_You're_Searching"
file_name = open("file.txt")
for num, line in enumerate(file_name,1):
if lookup in line:
print(num)

