2010-11-05 100 views
6

有人能告訴我如何從Python中的文件中讀取隨機數的行嗎?從Python中的文件中讀取許多隨機行

+1

什麼是「隨機數行」的範圍?偏移量也是隨機的嗎? – 2010-11-05 12:27:39

+5

「許多隨機線條」和「隨機數線條」是完全不同的東西。 – 2010-11-05 13:08:45

回答

16

你的要求是有點模糊,所以這裏的另一種略有不同的方法(靈感,如果沒有別的):

from random import random 
lines = [line for line in open("/some/file") if random() >= .5] 

與其他解決方案相比,行數變化較小(分佈在總行數的一半左右),但每行選擇的概率爲50%,並且只需要傳遞一個文件。

+0

+1我很喜歡這個解決方案。 – aaronasterling 2010-11-05 12:39:00

+0

'random.random()> .5'在這裏有什麼意義? – user225312 2010-11-05 12:40:43

+0

'random()'返回一個0到1之間的隨機數,並且分佈均勻。 random()> .5'將在一半的時間±正態分佈,即每條線以50%的概率被選擇。 – SimonJ 2010-11-05 12:44:13

0
import os,random 

def getrandfromMem(filename) : 
    fd = file(filename,'rb') 
    l = fd.readlines() 
    pos = random.randint(0,len(l)) 
    fd.close() 
    return (pos,l[pos]) 

def getrandomline2(filename) : 
    filesize = os.stat(filename)[6] 
    if filesize < 4096 : # Seek may not be very useful 
    return getrandfromMem(filename) 

    fd = file(filename,'rb') 
    for _ in range(10) : # Try 10 times 
    pos = random.randint(0,filesize) 
    fd.seek(pos) 
    fd.readline() # Read and ignore 
    line = fd.readline() 
    if line != '' : 
     break 

    if line != '' : 
    return (pos,line) 
    else : 
    getrandfromMem(filename) 

getrandomline2("shaks12.txt") 
+0

你也可以檢查 http://www.bryceboe.com/2009/03/23/random-lines-from-a-file/ – 2010-11-05 12:25:57

0

假設偏移總是在文件的開頭:

import random 
lines = file('/your/file').read().splitlines() 
n_lines = random.randrange(len(lines)) 
random_lines = lines[:n_lines] 

注意,這將整個文件讀入內存中。

+0

這將只會返回前n行。 – aaronasterling 2010-11-05 12:38:07

2
import linecache 
import random 
import sys 


# number of line to get. 
NUM_LINES_GET = 5 

# Get number of line in the file. 
with open('file_name') as f: 
    number_of_lines = len(f.readlines()) 

if NUM_LINES_GET > number_of_lines: 
    print "are you crazy !!!!" 
    sys.exit(1) 

# Choose a random number of a line from the file. 
for i in random.sample(range(1, number_of_lines+1), NUM_LINES_GET) 
    print linecache.getline('file_name', i) 

linecache.clearcache() 
+0

這不是隨機的行數。 – aaronasterling 2010-11-05 12:36:24

+0

@aaronasterling:呃?也許我沒有很好地理解這個問題,但他要求隨機數字的行不是隨機行的數字嗎? – mouad 2010-11-05 12:39:06

+0

你總是會返回5行,而5不是很隨意:)但我同意,問題很模糊。 – SimonJ 2010-11-05 12:41:44

12

爲了得到多條線路從您的文件進行隨機你可以做類似如下:

import random 
with open('file.txt') as f: 
    lines = random.sample(f.readlines(),5) 

上面的例子返回5行,但你可以很容易地改變你的需要數量。您也可以將其更改爲randint()以獲得隨機數量的行以及多個隨機行,但您必須確保樣本大小不超過文件中的行數。根據您的輸入,這可能是微不足道的,或者更復雜一點。

請注意,行可能以lines的順序出現在文件中。