如何知道使用随机库从数组中选择了什么项目?
How to know what item is chosen from array using random library?
我正在尝试制作一个机器人来询问一个人的基本 true/false 问题。我有两个 .txt
文件(一个有问题,一个有答案),我打开它们然后读取并从中删除换行符 '\n'
。这是我阅读问题文件的代码:
import random
engine = pyttsx3.init()
with open('read_ques.txt', 'r') as file:
data_ques = file.read().replace('\n', '')
data1 = data_ques.split('? ')
random_ques = random.choice(data1)
print(random_ques)
问题是我不知道 random.choice()
会从问题 .txt
文件中选择什么问题,所以我无法判断这个人的答案是否正确或错误。
这是我的每个文件中的几行。
问题文件:
Chameleons have extremely long tongues sometimes as long as their bodies, True or False?
An ostrichs eye is bigger than its brain, True or False?
A sneeze is faster than the blink of an eye, True or False?.
Pigs can look up into the sky, True or False?
答案文件:
Answer: True.
Answer: True.
Answer: True.
Answers: False (They cannot).
第 1 行问题(在问题文件中)= 第 1 行答案(在答案文件中)
第 2 行问题(在问题文件中)= 第 2 行答案(在答案文件中)
等等
由于行号将两个文件中的问题和答案相关联,我会生成一个随机行号并使用它来索引一个随机问题及其相应的答案。
import random
with open('questions.txt', 'r') as file:
questions = file.read().split('\n')
with open('answers.txt', 'r') as file:
answers = file.read().split('\n')
random_idx = random.randint(0, len(questions) - 1)
question = questions[random_idx]
answer = answers[random_idx]
我正在尝试制作一个机器人来询问一个人的基本 true/false 问题。我有两个 .txt
文件(一个有问题,一个有答案),我打开它们然后读取并从中删除换行符 '\n'
。这是我阅读问题文件的代码:
import random
engine = pyttsx3.init()
with open('read_ques.txt', 'r') as file:
data_ques = file.read().replace('\n', '')
data1 = data_ques.split('? ')
random_ques = random.choice(data1)
print(random_ques)
问题是我不知道 random.choice()
会从问题 .txt
文件中选择什么问题,所以我无法判断这个人的答案是否正确或错误。
这是我的每个文件中的几行。
问题文件:
Chameleons have extremely long tongues sometimes as long as their bodies, True or False?
An ostrichs eye is bigger than its brain, True or False?
A sneeze is faster than the blink of an eye, True or False?.
Pigs can look up into the sky, True or False?
答案文件:
Answer: True.
Answer: True.
Answer: True.
Answers: False (They cannot).
第 1 行问题(在问题文件中)= 第 1 行答案(在答案文件中)
第 2 行问题(在问题文件中)= 第 2 行答案(在答案文件中) 等等
由于行号将两个文件中的问题和答案相关联,我会生成一个随机行号并使用它来索引一个随机问题及其相应的答案。
import random
with open('questions.txt', 'r') as file:
questions = file.read().split('\n')
with open('answers.txt', 'r') as file:
answers = file.read().split('\n')
random_idx = random.randint(0, len(questions) - 1)
question = questions[random_idx]
answer = answers[random_idx]