繁体   English   中英

如何在 Python 中存储用户输入并稍后调用?

[英]How to store user input in Python and call it later?

我想做一个能记住一些东西并且可以在以后展示的程序——比如人工智能

首先,我将向程序展示问题,例如“你今天过得怎么样?” 我还教它回答“好吧,你?”,类似的。

第二,当我问节目“你今天过得怎么样?” 或者“你好吗?”,它应该知道答案。

到目前为止,我有这个:

print ("Salut ! Am nevoie de ajutorul tau sa invat cateva propozitii...")
print ("Crezi ca ma poti ajuta ?")
answer1 = input("da/nu")

if (answer1=="da"):
  print ("Bun , acum tu poti sa pui intrebarea si raspunsul")
  print ("Spre exemplu , Primul lucru la inceput de linie trebuie sa fie intrebarea urmata de *?* ")
  print ("Apoi , raspunsul pe care eu trebuie sa il dau.")
  print ("Exemplu : Intrebare= Ce faci ? Raspuns= Bine , mersi :D")
question= "asd"
while (question != "stop"):
  question = input("The question: ")
  answer = input("The answer= ")

我应该怎么做才能存储问题,相应问题的答案,然后,当我输入诸如“密码”或任何特定单词之类的内容以测试它是否知道回答我的问题时?

尝试字典数据结构。 这种结构允许快速检索给定键(问题)的值(答案)。 这是一个示例程序和输出:

# dictionary to store the question-answer pairs
qa = {}

# store a series of question/answer pairs
while 1:
    question = input("add a question (or q to quit): ")

    if question == "q": 
        break

    answer = input("add the answer: ")
    qa[question] = answer

print("...")

# run the quiz
while 1:
    question = input("ask me a question (or q to quit): ")

    if question == "q": 
        break
    elif question in qa:
        print(qa[question])
    else:
        print("i'm not sure...")

示例运行:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

add a question (or q to quit):  what is the meaning of life?
add the answer:  42
add a question (or q to quit):  what is my password?
add the answer:  1234
add a question (or q to quit):  q
...
ask me a question (or q to quit):  what is the meaning of life?
42
ask me a question (or q to quit):  what is my password?
1234
ask me a question (or q to quit):  help?
i'm not sure...
ask me a question (or q to quit):  q

如果您需要在程序运行后保留这些问题, 请将您的qa dict 写入文件或将问题和答案存储在SQLite等数据库中。

您可以使用字典

answers = dict()
# usage is answers[question] = answer;
answers['How are you?'] = 'Good'
question = input()
if question in answers:
 print(answers[question])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM