2014-10-06 3 views
0

파이썬의 텍스트 파일에서 임의의 줄을 읽는 함수를 만들어야합니다.텍스트 파일에서 임의로 한 줄을 읽는 기능

나는 다음과 같은 코드를 가지고 있지만 얻을 수 아니다는

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)) 

을 일을 내가 지금까지 가지고 있지만, 프로그램은 내가 '실행되면

도와주세요, 더 갈 도움이 필요합니다 오류가 발생했습니다.

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

현재 직면 한 오류 또는 문제는 무엇입니까? – OregonTrail

+0

무엇이 오류입니까? 귀하의 질문에 스택 추적을 붙여주십시오. – OregonTrail

+1

'print (randomLine (testfile.txt))''testfile.txt'는 따옴표가 필요하므로 문자열이됩니다. –

답변

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() 
관련 문제