我在一个文本文件中有一些问题,我想一一阅读。文本文件是列表中已读的问题。在讨论了显示的第一个问题之后,该程序应允许我触发下一个问题。问题应该随机出现。
现在,我有执行此任务的脚本,但是每次必须运行该程序时,就好像我是第一次运行它。
下面是我的代码:
import random
with open('questions.txt', 'r') as f:
text = f.read()
list_of_qns = text.splitlines()
if len(list_of_qns) != 0:
question = random.choice(list_of_qns)
print(question)
list_of_qns.remove(question)
请帮助我使它一次运行一个问题,如果列表仍然有问题,请不要终止它。另请注意,我删除了我们已完成的问题,以防止在同一运行中多次显示该问题。
答案 0 :(得分:3)
您可以使用random.shuffle来随机整理问题列表。
此外,您可以使用readlines
以行列表的形式直接读取文件,而不是稍后读取并分割文件。
import random
with open('questions.txt', 'r') as f:
questions = f.readlines()
random.shuffle(questions)
for question in questions:
print(question)
如果您要进行多个会话,则可以定义一个函数:
def ask_all_questions:
random.shuffle(questions)
for question in questions:
print(question)
每次调用它时,都会以随机顺序再次询问所有问题。
答案 1 :(得分:1)
您可以尝试以下方法:
$("#draftcontent").text()
按Enter键转到下一个问题。
答案 2 :(得分:0)
使用while代替if
import random
with open('questions.txt', 'r') as f:
text = f.read()
list_of_qns = text.splitlines()
while len(list_of_qns) != 0:
question = random.choice(list_of_qns)
print(question)
list_of_qns.remove(question)
同时,您可以循环播放,直到不再满足 条件为止。
对于用户输入,您可以使用类似以下内容的
:inp = input()
答案 3 :(得分:0)
import random
# reads questions text
with open('questions.txt', 'r') as f:
text = f.read()
# converts into text format
list_of_qns = text.splitlines()
# length of list_of_questions
number_of_questions = len(list_of_questions)
# create dcitionary to check question printed or not
dict_of_questions_printed = dict()
# for not printed question mark intially as 1
for question in list_of_qns:
dict_of_questions_printed[question] = 1
# loop until number_of_questions is not equal to 0
while number_of_questions != 0:
# select random question
question = random.choice(list_of_qns)
# checks if question is printed or value in dictionary is 0 continues
if not dict_of_questions_printed[question]:
continue
# else prints question, marks dictionary value of question to 0 and
# decrements number of question
print(question)
dict_of_questions_printed[question] = 0
number_of_question -= 1
continue