/
IDMIRT
/
Chat-bot
Обзор
Документация
Войти
/
IDMIRT
/
Chat-bot
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/functions.py
105 строк
3 KB
Дмитрий Иванов
окончательный вариант с real
03 июн 2026, 16:23
03 июн 2026, 16:23
fea2da5
Код
Авторство
О чём код?
from random import choice from math import sqrt math_operations = {'+':'+','-':'-','/':'/','*':'*', 'плюс':'+','минус':'-','умножить':'*','разделить':'/', 'в степени':'^','^':'^','√':'√'} do_operation = {'+':lambda x, y: x + y, '-':lambda x, y: x - y, '*':lambda x, y: x * y, '/':lambda x, y: x / y, '^':lambda x, y: x ** y, '√':lambda x: sqrt(x)} symbols_math_operations = list(math_operations.keys()) letter_for_math = [str(x) for x in range(0,10)]+list(math_operations.values()) class ErrorMathSymbols(Exception): pass def is_float(str_num): try: return float(str_num) and '.' in str_num except ValueError: return False def is_number(num): if num.isdigit(): return int(num) elif is_float(num): return float(num) else: raise ValueError(f'{num} не является числом') def extract_numbers(message): global letter_for_math letters_math = letter_for_math+['.'] list_message = [x for x in message if x in letters_math] math_message = ''.join(list_message) for do_math in symbols_math_operations: if do_math in math_message: if do_math == '-' and math_message.index(do_math) !=0: continue else: index_symbol = math_message.find(do_math) break math_operation = math_message[index_symbol] first_num = is_number(math_message[:index_symbol:]) second_num = is_number(math_message[index_symbol+1::]) return first_num,second_num,math_operation def check_math_operation(message): if not any(symbol in message.lower() for symbol in symbols_math_operations): raise ErrorMathSymbols(f'В строке "{message}" нет математических операторов') else: return True def operation(message): first_num = None second_num = None math_operation = None for key, value in math_operations.items(): if key in message: message = message.replace(key,value) try: if check_math_operation(message): first_num,second_num,math_operation = extract_numbers(message) if math_operation == '√': result = do_operation[math_operation](first_num) else: result = do_operation[math_operation](first_num,second_num) except(ErrorMathSymbols) as e: return e return result def chat_bot(message,answers,language): unknow_answer = {"русский":"Извините, я не знаю как ответить на это", "english":"Sorry, I do not know how to answer this."} if "вычисли" in message.lower(): responce = operation(message) else: responce = choice(answers[language].get(message.lower(),unknow_answer[language])) if responce == unknow_answer: responce = choice(answers[language]["randoms"]) return responce