from flask import Flask, render_template, request
app = Flask(__name__)
# 一个简单的问题-答案映射,实际中可以使用更复杂的存储结构(数据库等)
qa_pairs = {
"什么是人工智能?": "人工智能是模拟人类智能的一种机器系统。",
"机器学习是什么?": "机器学习是一种人工智能的应用,让计算机具备学习能力。",
# 其他问题和对应的答案
}
@app.route('/')
def home():
return render_template('index.html')
@app.route('/ask', methods=['POST'])
def ask():
user_input = request.form['user_input']
answer = qa_pairs.get(user_input, "抱歉,暂时无法回答您的问题。")
return render_template('index.html', question=user_input, answer=answer)
if __name__ == '__main__':
app.run(debug=True)
When it comes to larger projects, the complete code may be longer and contain multiple files. The following is a sample code for a simple text question and answer system based on the Flask framework, including a simple front-end interface and back-end processing:
First, install Flask and other necessary libraries:
l
Template file used to display a simple front-end interface. Here is a simple index.html
example
<!DOCTYPE html>
<html>
<head>
<title>文本问答系统</title>
</head>
<body>
<h1>简单文本问答系统</h1>
<form method="POST" action="/ask">
<label for="user_input">请输入问题:</label><br>
<input type="text" id="user_input" name="user_input"><br>
<input type="submit" value="提交">
</form>
{% if question %}
<p><strong>您的问题:</strong>{
{ question }}</p>
<p><strong>回答:</strong>{
{ answer }}</p>
{% endif %}
</body>
</html>
Save and run the above code, and then access it in the browser http://127.0.0.1:5000/
to see a simple text question and answer system interface. The user enters a question in the input box, and the system will answer according to the preset question-answer mapping.
Please note that this is just a simple example. In fact, a real text question answering system will be more complex and needs to be implemented using more complex natural language processing technology (such as natural language processing models or knowledge graphs).