简体   繁体   中英

Accessing random lines from a text file - Python

I am creating a test like program and have a text file under QAfile that can be added to, with one line containing a question and the next line containing the corresponding answer. I would like to be able to output a random line containing a question and then the corresponding answer (from the next line) with questions being on even number lines (inc 0). How would I be able to output a random even numbered line with a question from the text file and then the corresponding answer in the following function ?

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

The problem you face is, that to know about the lines you have to read through the entire file. Should speed be an issue, there are various other methods to speed up counting the lines depending on the system you are using and your willingness to use shell commands from Python.

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

PS Thanks to Adam Smith (see comments) for his efforts in improving this answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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