我正在创建一个类似测试的程序,并且在 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/