python - 从文本文件访问随机行 - Python

标签 python python-3.x file tkinter text-files

我正在创建一个类似测试的程序,并且在 QAfile 下有一个可以添加的文本文件,其中一行包含问题,下一行包含相应的答案。我希望能够输出包含问题的随机行,然后输出相应的答案(从下一行开始),问题位于偶数行(inc 0)。我如何能够输出一个随机偶数行,其中包含文本文件中的问题,然后在以下函数中输出相应的答案?

def TestMe():

    global QAfile
    global questionloc
    global answerloc
    global data

    try:
        with open(QAfile, 'r') as f:
            rootQA = Tk()
            rootQA.title('Question time')
            data = f.read().splitlines()
            lineNO = len(data)
            questionloc = random.randrange(0, lineNO, 2)     
            answerloc = questionloc + 1                      
            for questionloc in data:                         
                qlbl = Label(rootQA, text=data[questionloc]) 
                qlbl.pack()

                answerB = Button(rootQA, text='Answer?', command=Answer)
                answerB.grid(columnspan=10, sticky=W)
                answerB.pack(fill = 'x')

                repeatB = Button(rootQA, text='Another question', command=TestMe)
                repeatB.grid(columnspan=10, sticky=W)
                repeatB.pack(fill = 'x')

                HomeB = Button(rootQA, text='Done', command=LoggedIn)
                HomeB.grid(columnspan=10, sticky=W)
                HomeB.pack(fill = 'x')

def Answer():

    global data
    global answerloc

    with open(data) as f:
        rootA = Tk()
        rootA.title('Answer')
        Albl = Label(rootA, text=f[answerloc])    
        Albl.pack()
        rootA.mainloop()

最佳答案

您面临的问题是,要了解这些行,您必须通读整个文件。如果速度是一个问题,还有各种其他方法可以加快行数计数,具体取决于您使用的系统以及您是否愿意使用 Python 的 shell 命令。

def get_q_a(fname):
    with open(fname) as f:
        numlines = sum(1 for _ in f)
    from random import choice
    target_line = choice(range(0, numlines-1, 2))
    with open(fname) as f:
        for _ in range(target_line):
            next(f)
        question, answer = next(f), next(f)
    return (question, answer)

question, answer = get_q_a('qaFile.txt')

# now there is question and answer available for further processing

附注感谢Adam Smith(见评论)为改进这个答案所做的努力。

关于python - 从文本文件访问随机行 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43696402/

相关文章:

python - 在python中使用用户定义的转换函数将灰度图像转换回rgb图像的问题

python-3.x - 如何通过 API 接受 Github 仓库邀请?

file - 如何打开最有可能是二进制的 LUA 文件?

python - 奇怪的 numpy.float96 行为

python - 非零函数帮助,Python Numpy

python - 理解 : multiple values per iteration

python - Pygame:如何让两个物体在碰撞后停止移动

c# - 带有空格的路径无法使用 File.CreateText(filePath) c# 创建文件

c++ - 在当前目录中打开一个文件

python - 如何在Python中以特定的输出格式将矩阵(从一个文件读取)写入另一个csv文件