我正在创建一个类似程序的测试,并在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()
答案 0 :(得分:2)
您面临的问题是,了解您必须阅读整个文件的行。如果速度成为一个问题,根据您使用的系统以及您是否愿意使用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
P.S。感谢Adam Smith
(见评论)他努力改进这个答案。