import json
from difflib import get_close_matches
def load_data(file_path: str) -> dict:
“””Load data from a JSON file.”””
with open(file_path, “r”) as file:
data = json.load(file)
return data
def save_data(file_path: str, data: dict):
“””Save data to a JSON file.”””
with open(file_path, “w”) as file:
json.dump(data, file, indent=2)
def find_best_match(user_question: str, questions: list[str]) -> str | None:
“””Find the closest matching question from the list.”””
matches = get_close_matches(user_question, questions, n=1, cutoff=0.6)
return matches[0] if matches else None
def get_answer_for_questions(question: str, data_base: dict) -> str | None:
“””Retrieve the answer for a given question from the database.”””
for q in data_base[“questions”]:
if q[“question”] == question:
return q[“answer”]
return None
def chatbot_mainloop():
“””Main loop to interact with the chatbot.”””
# Load the database from a JSON file
data_base = load_data(“data_base.json”)
while True:
userinput = input("You: ")
if userinput.lower() == "quit":
break
# Find the best match for the user's question
best_match = find_best_match(userinput, [q["question"] for q in data_base["questions"]])
if best_match:
# If a best match is found, get the corresponding answer
answer = get_answer_for_questions(best_match, data_base)
print(f"Shervin: {answer}")
else:
print("I don't know the answer. Can you teach me?")
new_answer = input("Type your new answer or you can skip: ")
if new_answer.lower() != "skip":
# Append the new question and answer to the database
data_base["questions"].append({"question": userinput, "answer": new_answer})
save_data("data_base.json", data_base)
print("Shervin: Thank you, I learned something new.")
if name == “main“:
chatbot_mainloop()
this is my code
i cant append my data from python to json using dict. the issue is in 6th line from the bottom
in chatbot_mainloop
data_base[“questions”].append({“question”: userinput, “answer”: new_answer})
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: ‘dict’ object has no attribute ‘append’
this is the error that my vscode terminal gave me
i was watching a youtube tutorial. i used the source code as well but the source code gave the same error
user26591679 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.