我必须创建一个从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))
我到目前为止,但需要帮助才能更进一步,请帮助
程序运行后,我收到错误
print(randomLine(testfile.txt))
NameError: name 'testfile' is not defined
答案 0 :(得分: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()