Reputation: 347
I am trying to make a bot that asks a person s basic true/false questions. I have two .txt
files (one with questions and one with answers) which I open then read and remove the new line character '\n'
from. This is my code for reading the questions file:
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)
The problem is that I don't know what question random.choice()
will choose from the questions .txt
file, so I can't tell if the person was correct about if the answer was true or false.
Here are a few lines from each of my files.
Questions file:
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?
Answers file:
Answer: True.
Answer: True.
Answer: True.
Answers: False (They cannot).
line 1 question(in questions file) = line 1 answer(in answers file)
line 2 question(in questions file) = line 2 answer(in answers file) etc.
Upvotes: 1
Views: 176
Reputation: 2266
Since line numbers correlate questions and answers in the two files, I would generate a random line-number and use that to index a random question and its corresponding answer.
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]
Upvotes: 1