编写问答程序可以根据不同的需求和场景采用不同的方法。以下是几种常见的方法和示例代码:
方法一:使用Python编写简单的问答程序
```python
def ask_question(question):
"""根据问题返回相应的回答"""
if question == "你叫什么名字?":
return "我叫小助手"
elif question == "你几岁了?":
return "我是一个程序,没有年龄"
elif question == "你喜欢什么颜色?":
return "我喜欢蓝色"
else:
return "我不知道答案"
def main():
while True:
question = input("请输入一个问题(输入'退出'结束程序): ")
if question == "退出":
break
answer = ask_question(question)
print(answer)
if __name__ == "__main__":
main()
```
方法二:使用ZeroMQ实现简单的问答系统
服务端代码:
```python
import zmq
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5555")
while True:
msg = socket.recv_string()
print(f"收到问题: {msg}")
answer = "没问题,搞定!"
socket.send_string(answer)
```
客户端代码:
```python
import zmq
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5555")
while True:
question = input("请输入一个问题: ")
socket.send_string(question)
answer = socket.recv_string()
print(f"收到回答: {answer}")
```
方法三:使用Tkinter和SQLite设计问答程序
```python
import tkinter as tk
from tkinter import messagebox
import sqlite3
def create_database():
conn = sqlite3.connect('quiz.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS quiz
(id INTEGER PRIMARY KEY AUTOINCREMENT,
question TEXT NOT NULL,
answer TEXT NOT NULL)''')
conn.commit()
conn.close()
def add_question():
question = question_entry.get()
answer = answer_entry.get()
conn = sqlite3.connect('quiz.db')
c = conn.cursor()
c.execute("INSERT INTO quiz (question, answer) VALUES (?, ?)", (question, answer))
conn.commit()
conn.close()
messagebox.showinfo("成功", "问题已添加!")
def show_questions():
conn = sqlite3.connect('quiz.db')
c = conn.cursor()
c.execute("SELECT * FROM quiz")
questions = c.fetchall()
conn.close()
question_list.delete(1.0, tk.END)
for question in questions:
question_list.insert(tk.END, f"{question}\n")
root = tk.Tk()
root.title("二次元浓度测试")
create_database()
frame = tk.Frame(root)
frame.pack()
question_label = tk.Label(frame, text="问题:")
question_label.pack()
question_entry = tk.Entry(frame)
question_entry.pack()
add_button = tk.Button(frame, text="添加问题", command=add_question)
add_button.pack()
question_list = tk.Text(frame, height=10, width=50)
question_list.pack()
show_button = tk.Button(frame, text="显示问题", command=show_questions)
show_button.pack()
root.mainloop()
```
方法四:使用Python编写基于字典的问答系统