获取文本文件中特定短语的行号
我需要在一个文本文件中找到某个短语的行号。这个短语可能是:
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"
这不是作业,而是我正在做的一个项目的一部分。我甚至不知道怎么才能得到行号。
11 个回答
7
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
print get_line_number("the dog barked", "C:/file.txt") # python2
#print(get_line_number("the dog barked", "C:/file.txt")) # python3
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。
13
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
来打开文件是Python的推荐做法——这样可以确保在使用文件的代码块结束时,文件会被正确关闭。 - 用
for line in f
来逐行读取文件比用for line in f.readlines()
要好得多。前者是Python的做法(比如说,如果f
是任何可迭代对象,这种方式都能工作;不一定非得是实现了readlines
的文件对象),而且效率更高。因为f.readlines()
会把整个文件读入内存,创建一个列表,然后再逐行处理。*if search_phrase in line
比if line.find(search_phrase) >= 0
更符合Python的风格,因为它不需要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一样写代码
133
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
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。