【问题标题】:How to know what item is chosen from array using random library?如何知道使用随机库从数组中选择了哪些项目?
【发布时间】:2022-01-01 01:27:30
【问题描述】:

我正在尝试制作一个机器人来询问一个人的基本真/假问题。我有两个.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 行答案(在答案文件中) 等等

【问题讨论】:

  • random_ques 是选择的问题,与转换后的语音相比,您有什么困难?还是您的问题是文本文件不包含该问题的答案?因为它应该,所以您应该在文本文件中同时包含问题和答案
  • 获取一个随机数(介于 0 和问题数量之间)并使用该索引获取文本和答案。
  • @Jeppe 为什么使用索引并通过该索引访问列表? random.choice 已经这样做了
  • 创建自己的架构:例如每行都有“Q:[问题文本] A:[true/false]”——为此使用 JSON 而不是纯文本可能值得。
  • 有一个像这样的结构(有很多不同的方法来做到这一点)question? answer\n(在文本编辑器中你不会看到换行符,但你会把光标放在一个新行),因此您可以将文件文本按'\n' 拆分以获得所有答案和问题,然后当choice 选择其中一对时,将该对按'? ' 拆分,第一项将是问题,第二项项目将是答案

标签: python random


【解决方案1】:

由于行号与两个文件中的问题和答案相关联,我将生成一个随机行号并使用它来索引一个随机问题及其相应的答案。

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]

【讨论】:

  • 很好的答案!该程序运行了很长时间,直到我收到此错误Traceback (most recent call last): File "c:/Users/user/Desktop/talk_bot/hello.py", line 13, in <module> question = questions[random_idx] IndexError: list index out of range 我在一个真正的循环中添加了以下代码print(question) if input("What is the answer? ").lower().startswith(answer): print("Right answer") else: print("Wrong Answer"),并将random_idxquestionanswer 变量也放入循环中.任何想法正在发生的事情。
  • @jjoa 我更新了答案,现在是random.randint(0, len(questions) - 1)。我忘了这个功能是包容性的。您还应该检查问题和答案列表的长度是否相等。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多