2014-10-06 175 views
0

我必須創建一個從python中的文本文件讀取隨機行的函數。從文本文件中隨機讀取一行的函數

我有下面的代碼,但我無法得到它的工作

import random 

def randomLine(filename): 
    #Retrieve a random line from a file, reading through the file irrespective of the length 
    fh = open(filename.txt, "r") 
    lineNum = 0 
    it = '' 

    while 1: 
     aLine = fh.readline() 
     lineNum = lineNum + 1 
     if aLine != "": 

      # How likely is it that this is the last line of the file ? 
      if random.uniform(0,lineNum)<1: 
       it = aLine 
     else: 
      break 

    fh.close() 

    return it 
print(randomLine(testfile.txt)) 

我走到這一步,但是,需要幫助走得更遠,請幫

一旦程序運行我」 m得到錯誤說

print(randomLine(testfile.txt)) 
NameError: name 'testfile' is not defined 
+0

您目前遇到的錯誤或問題是什麼? – OregonTrail 2014-10-06 02:55:18

+0

什麼是錯誤?請將堆棧跟蹤粘貼到您的問題中。 – OregonTrail 2014-10-06 02:58:12

+1

'print(randomLine(testfile.txt))'你需要''testfile.txt'周圍的引號,以便它變成一個字符串。 – 2014-10-06 03:01:52

回答

0

這是一個已經過測試的版本,可以避免空行。

爲清楚起見,變量名稱是詳細的。

import random 
import sys 

def random_line(file_handle): 
    lines = file_handle.readlines() 
    num_lines = len(lines) 

    random_line = None 
    while not random_line: 
     random_line_num = random.randint(0, num_lines - 1) 
     random_line = lines[random_line_num] 
     random_line = random_line.strip() 

    return random_line 

file_handle = None 

if len(sys.argv) < 2: 
    sys.stderr.write("Reading stdin\n") 
    file_handle = sys.stdin 
else: 
    file_handle = open(sys.argv[1]) 

print(random_line(file_handle)) 

file_handle.close()