15.
Implement a simple chatbot for answering python questions from
text file.
app.py
from flask import Flask, request, render_template
app = Flask(__name__)
def load_questions():
questions = {}
with open('python_questions.txt', 'r') as file:
lines = file.readlines()
for line in lines:
question, answer = line.strip().split('|||')
questions[question.strip()] = answer.strip()
return questions
python_questions = load_questions()
@app.route('/')
def chatbot_page():
return render_template('chatbot.html')
@app.route('/ask', methods=['POST'])
def answer_question():
user_question = request.form.get('user_question')
if user_question in python_questions:
answer = python_questions[user_question]
else:
answer = "Sorry, I don't know the answer to that question."
return render_template('chatbot.html', user_question=user_question,
answer=answer)
if __name__ == '__main__':
app.run(debug=True)
python_questions.txt
What is Python? ||| Python is a high-level programming
language.
How to declare a variable in Python? ||| You can declare a
variable in Python using the assignment operator (=).
Chatbot.html
<!DOCTYPE html>
<html>
<head>
<title>Python Chatbot</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.mi
n.css">
</head>
<body>
<div class="container mt-5">
<h1>Python Chatbot</h1>
<form method="POST" action="/ask">
<div class="form-group">
<label for="user_question">Ask a Python question:</label>
<input type="text" class="form-control" id="user_question"
name="user_question" required>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% if user_question %}
<h3>Your Question:</h3>
<p>{{ user_question }}</p>
<h3>Answer:</h3>
<p>{{ answer }}</p>
{% endif %}
</div>
</body>
</html>