如何选择json或python中的任何内容? [已关闭]

问题描述 投票:0回答:1

我正在用 JSON 为 Python 聊天机器人编写一些数据,这是我的 JSON 结构/格式:

"question": "add question here",
"answers": [
"answers here"
]
"correctAnswer": 0

那么有谁知道如何选择任何一个答案,例如问候语?预先感谢!

python json data-structures chatbot
1个回答
0
投票
  1. 向您的 json 文件添加更多答案。
  2. 将 json 文件加载到你的 python 程序中。
  3. 使用
    random.choice
    随机选择任何答案。

数据.json

{
    "question": "add question here",
    "answers": [
        "answers here",
        "another answer here",
        "third answer here"
    ],
    "correctAnswer": 0
}

主.py

import random
import json

with open("data.json", "r") as f:
    data = json.load(f)

print(random.choice(data["answers"]))
© www.soinside.com 2019 - 2024. All rights reserved.