Python recipe(8): Retieve line from file

代码何在?

div css xhtml xml Example Source Code Example Source Code [http://www.cnblogs.com/tomsheep/]
'''
Created on 2010-5-22

@author: lk
'''
import linecache,random

#given the line number, retrieve the line
def getline1(filename, line_num):
    return linecache.getline(filename, line_num)

def getline2(filename, line_num):
    if line_num<1:return ''
    cur_pos = 0
    for line in open(filename):
        cur_pos+=1
        if cur_pos == line_num:
            return line
#return one line from file object randomly        
def randomLine1(file_obj):
    return random.choice(file_obj.readlines())

def randomLine2(file_obj):
    num = 0
    select = ''
    while 1:
        line = file_obj.readline()
        if not line:break
        num += 1
        if random.uniform(0,num)<1:
            select = line
    file_obj.close()
    return select
        
if __name__ == '__main__':
    print getline1('test.txt',2)
    print getline2('test.txt',2)
    
    print randomLine1(open('test.txt'))
    print randomLine2(open('test.txt'))

以上代码改写自Python Cookbook 4-5/4-6

概述:

    从文件中读取一行。getline函数返回指定行号的内容,randomLine随机返回一行。两种功能都分别用了两种方法实现。

代码说明:

1. getline1:使用linecache模块提供的函数,一般情况用这个效率就很好。但由于它的默认操作时将整个文件读进cache,如果文件很大,而你只想要一行,会比较废

2. getline2:用简单的循环实现

3. randomLine1: 使用random模块的choice函数实现,和getline1差不多,文件很大的时候效率不好

4. randomLine2: 用循环实现。这里利用了一个小小的概率原理,if random.uniform(0,num)<1 这句是为了保证每一行被选到的概率都是1/N,N是所有行数。(比如选到第k行的概率就是 1/k×k/(k+1)×(k+1)/(k+2)…×(N-1)/N = 1/N

5. random.choice 返回给定list中的随机一项

6. random.uniform(a,b)返回[a,b)区间内的随机实数

posted on 2010-05-22 17:56  tomsheep  阅读(439)  评论(0编辑  收藏  举报

导航