2014-07-23 25 views
2

假設你有一個非常大的文件,並且通過所有行或者減慢它的開銷會很高。從一個非常大的文件中從命令行中挑選一個隨機行

你會隨機選擇一條線(最好是從命令行或python)?

+3

這是不可能來接從文件中隨機線不知道時間提前多少行是該文件,其中每行開始英寸否則,您必須閱讀整個文件。請參閱http://stackoverflow.com/questions/232237/whats-the-best-way-to-return-a-random-line-in-a-text-file-using-c以獲取靈感。 –

+1

您可以使用_wc_和_sed_ ..看看t jim的回答 –

+0

行長限制在整個文件中是不變的? – moooeeeep

回答

1

你可以從命令行嘗試這個 - 不確定是否完全隨機,但至少是一個開始。

$ lines=$(wc -l file | awk '{ print $1 }'); sed -n "$((RANDOM%lines+1))p" file 

這是這樣工作的:

  • 首先,它設置包含在文件中的行數的變量。

    lines=$(wc -l file | awk '{ print $1 }') 
    
  • 後來,它打印在該範圍內的隨機行:

    sed -n "$((RANDOM%lines+1))p" file 
    

正如馬克蘭塞姆指出的那樣,在上述溶液中讀取整個文件。我找到了一種方法來選擇一個沒有(必然)必須讀取整個文件的隨機行,但只是其中的一部分。使用(我認爲)相同的算法,這裏是鏈接到兩個Perl和Python的解決方案:

  • 的Perl:How do I pick a random line from a file?

    perl -e 'srand;' \ 
        -e 'rand($.) < 1 && ($it = $_) while <>;' \ 
        -e 'print $it' FILE 
    
  • 的Python:Retrieving a Line at Random from a File of Unknown Size

    import random 
    
    def randomLine(file_object): 
        "Retrieve a random line from a file, reading through the file once" 
        lineNum = 0 
        selected_line = '' 
    
        while 1: 
         aLine = file_object.readline() 
         if not aLine: break 
         lineNum = lineNum + 1 
         # How likely is it that this is the last line of the file? 
         if random.uniform(0,lineNum)<1: 
          selected_line = aLine 
        file_object.close() 
        return selected_line 
    
+1

'wc'將讀取整個文件,'sed'將讀取所選擇的行。這在技術上回答了這個問題,但違反了規定的限制。 –

+0

@MarkRansom,你是對的 - 我已經更新了我的答案:) –

0

如果你想在python中做到這一點。這個給你。

#!/usr/bin/env python 
#-*- coding:utf-8 -*- 

import os 
import random 

def test(): 
    filename = 'yourfile' 
    info = os.popen('wc -l filename').readlines() 
    line_number = info[0].split()[0] 

    r = random.randrange(line_number) 
    cmd = 'sed -n "%dp" %s' % (r, filename) 
    info = os.popen(cmd).readlines() 

    print info 



if __name__ =='__main__': 

    test() 
0

可能是你可以使用linecache,

import linecache 
linecache.getline(file_path, line_no) 
相關問題