我需要在文本文件中获取短语的行号.这句话可能是:
the dog barked
Run Code Online (Sandbox Code Playgroud)
我需要打开文件,搜索该短语并打印行号.
我在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"
Run Code Online (Sandbox Code Playgroud)
这不是作业,它是我正在进行的项目的一部分.我甚至不知道如何获得行号.
Sac*_*cha 89
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
编辑1.5年后(看到它得到另一个upvote):我将离开这个原样; 但如果我今天写作会写一些更接近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
Run Code Online (Sandbox Code Playgroud)
with打开文件是Python的成语-它确保该文件将在使用该文件的块结束正常关闭. for line in f比使用文件要好得多for line in f.readlines().前者是pythonic(例如,如果f是任何泛型可迭代的话可以工作;不一定是实现的文件对象readlines),并且更高效地f.readlines()创建一个列表,其中整个文件在内存中然后迭代它.*if search_phrase in line比更Python if line.find(search_phrase) >= 0,因为它并不需要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.) 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
121861 次 |
| 最近记录: |