-- 61.182.251.99 [2004-09-21 05:42:12]

Contents

1. 描述

# 描述

Retrieving a Line at Random from a File of Unknown Size

## 解决 Solution

We do need to read the whole file, but we don't have to read it all at once:

```   1 import random
2
3 def randomLine(file_object):
4     "顺序读取文件内容,取文件的随机一行"
5     lineNum = 0
6     selected_line = ''
7
8     while 1:
10         if not aLine: break
11         lineNum = lineNum + 1
12         # 是否选择本行？                      #译注：这里英语原文注释可能有错，根据程序逻辑译出
13         if random.uniform(0,lineNum)<1:    #译注: 算法的解释见讨论部分,请先考虑考虑,uniform函数用法附后
14             selected_line = aLine
15     file_object.close(  )
16     return selected_line
```

## 讨论 Discussion

`random.choice(file_object.readlines(  ))`

Python 库参考 random模块部分

#译注：为阅读方便，这里给出random模块两个函数的说明

uniform( a, b) ：Return a random real number N such that a <= N < b.

choice( seq) ：Return a random element from the non-empty sequence seq.

PyCkBk-4-6 (last edited 2009-12-25 07:16:21 by localhost)

• Page.execute = 1.098s
• getACL = 0.183s
• init = 0.023s