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. Я также использовал исходный код, но исходный код выдал ту же ошибку.
[code]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() [/code] Это мой код. Я не могу добавить свои данные из Python в JSON с помощью dict. Проблема в 6-й строке снизу: [code]in chatbot_mainloop data_base["questions"].append({"question": userinput, "answer": new_answer}) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'dict' object has no attribute 'append' [/code] Это ошибка, которую выдал мой терминал VS Code. Я смотрел учебник на YouTube. Я также использовал исходный код, но исходный код выдал ту же ошибку.
Я пытаюсь создать музыку, используя собственный голос, и я впервые использую его и пишу код, и понятия не имею, почему я получаю эту ошибку.
вот мои зависимости:
pip install --upgrade pip !pip install torch numpy matplotlib scipy !pip install...
Я работаю над системой вопросов и ответов в формате PDF, используя LangChain и FAISS для векторного хранения. Однако во время процесса получения возникает ошибка:
Error during question answering: 'dict' object has no attribute 'search'