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