Объект «dict» не имеет атрибута «добавить» ошибкуPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Объект «dict» не имеет атрибута «добавить» ошибку

Сообщение Anonymous »

Код: Выделить всё

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()
Это мой код. Я не могу добавить свои данные из Python в JSON с помощью dict. Проблема в 6-й строке снизу:

Код: Выделить всё

in chatbot_mainloop
data_base["questions"].append({"question": userinput, "answer": new_answer})
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'dict' object has no attribute 'append'
Это ошибка, которую выдал мой терминал VS Code.
Я смотрел учебник на YouTube. Я также использовал исходный код, но исходный код выдал ту же ошибку.

Подробнее здесь: https://stackoverflow.com/questions/788 ... pend-error
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • AttributeError: объект «dict» не имеет атрибута «mask_padding» «model = Tacotron2(hparams)»
    Anonymous » » в форуме Python
    0 Ответы
    40 Просмотры
    Последнее сообщение Anonymous
  • Ошибка в PDF-вопросе-ответе: объект «dict» не имеет атрибута «поиск».
    Anonymous » » в форуме Python
    0 Ответы
    28 Просмотры
    Последнее сообщение Anonymous
  • Sqlalchemy select AttributeError: объект «dict» не имеет атрибута
    Anonymous » » в форуме Python
    0 Ответы
    21 Просмотры
    Последнее сообщение Anonymous
  • Sqlalchemy select AttributeError: объект «dict» не имеет атрибута
    Anonymous » » в форуме Python
    0 Ответы
    29 Просмотры
    Последнее сообщение Anonymous
  • Я получаю ошибку атрибута, так как объект «int 'не имеет атрибута» к'
    Anonymous » » в форуме Python
    0 Ответы
    3 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Python»