繁体   English   中英

从文本文件中随机读取一行的功能

[英]Function to randomly read a line from a text file

我必须创建一个从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

这是经过测试可以正常工作的版本,可避免出现空行。

为了清楚起见,变量名是冗长的。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM