Информатика — сложный предмет, и вы можете легко застрять. Кто-то, кто может помочь в этой ситуации, имеет решающее значение, потому что, если вы можете продолжать выполнять свои задачи, это сэкономит ваше время и усилия. Поэтому я сделал своего собственного бота. Бот специализируется на компьютерных науках. Я познакомлю вас с моим ботом «Friendly Zapp».
Я покажу вам, как он работает, в ближайшее время, но сначала я расскажу кое-что о том, как я сделал этого бота. Я использовал PyCharm для этого проекта. Язык, конечно, Python. Прежде чем смотреть на код, я хочу объяснить идею этого бота. Пользователь может ввести некоторые данные, например, вы можете сказать привет боту. Заранее вы уже создали ответы, которые относятся к определенному вопросу или комментариям. Бот вычисляет, какой ответ является лучшим, и отправляет его пользователю. Таким образом, пользователь и бот могут общаться друг с другом. Знания бота связаны с информатикой.
Код, который я сделал:
Первое, что я сделал, импортировал библиотеку и еще один файл. Я использовал два файла для этого бота, второй я объясню позже.
import re import long_responses as long
Я создал несколько функций, первая о том, какой ответ должен дать бот. Сначала программа подсчитывает количество слов в сообщении. Затем он собирается определить процент распознанных слов в сообщении.
def message_probability(user_message, recognised_words, single_response=False, required_words=[]): message_certainty = 0 has_required_words = True # Counts how many words are present in each predefined message for word in user_message: if word in recognised_words: message_certainty += 1 # Calculates the percentage of recognised words in a user message percentage = float(message_certainty) / float(len(recognised_words)) for word in required_words: if word not in user_message: has_required_words = False break if has_required_words or single_response: return int(percentage*100) else: return 0
Функция «ответ» является важной, для генерации ответов вам понадобится эта функция. Недостаток этого бота в том, что вам придется вносить ответы вручную. Конечно, есть способы автоматизировать это. (что-то на будущее)
def check_all_messages(message): highest_prob_list = {} def response(bot_response, list_of_words, single_response=False, required_words=[]): nonlocal highest_prob_list highest_prob_list[bot_response] = message_probability(message, list_of_words, single_response, required_words)
Здесь вы видите некоторые из возможных ответов. Ответ функции состоит из нескольких вещей, которые должен дать бот, слова, которые он должен искать, чтобы дать этот конкретный ответ, и которые должны быть произнесены, чтобы дать ответ. Если хорошего ответа нет, бот скажет, что не понимает ввода пользователя. Код для этой задачи отсутствует в этой части.
# Response -------------------------------------------- response('Hello!', ['hello', 'hi', 'sup', 'hey'], single_response=True) response('Im doing fine, and you?', ['how', 'are', 'you', 'doing'], required_words=['how']) response('Thank you!', ['i', 'love', 'Rick', 'Arentsen'], required_words=['Rick', 'Arentsen']) response('To answer questions about computer science', ['what', 'is', 'your', 'purpose'], required_words=['what', 'your', 'purpose']) response('You can ask me anything about computer science', ['what', 'can', 'i', 'ask', 'you'], required_words=['what', 'can', 'ask']) response('I answer all your question about computer science', ['tell', 'me', 'something'], required_words=['tell', 'me']) response(long.R_EATING, ['what', 'you', 'eat'], required_words=['you', 'eat']) response(long.R_CS, ['what', 'computer', 'science'], required_words=['computer', 'science']) response(long.R_LANGUAGE, ['which', 'languages', 'can', 'use', 'do', 'have'], required_words=['which', 'language']) response(long.R_POS, ['possibilities', 'what', 'are'], required_words=['what', 'possibilities']) response(long.R_AI, ['what', 'is', 'AI', 'artificial intelligence'], required_words=['what', 'AI']) response(long.R_VR, ['what', 'is', 'VR', 'virtual reality'], required_words=['what', 'VR']) response(long.R_WICS, ['what', 'parts', 'computer science'], required_words=['what', 'parts', 'computer science']) response(long.R_HW, ['what', 'is', 'hardware'], required_words=['what', 'hardware']) response(long.R_SW, ['what', 'is', 'software'], required_words=['what', 'software']) response(long.R_ALG, ['what', 'is', 'an', 'algorithm'], required_words=['what', 'algorithm']) response(long.R_DA, ['what', 'is', 'a', 'data structure'], required_words=['what', 'data structure']) response(long.R_GRA, ['what', 'is', 'a', 'grammar'], required_words=['what', 'grammar']) response(long.R_ARR, ['what', 'is', 'an', 'array'], required_words=['what', 'array']) response(long.R_DB, ['what', 'is', 'a', 'database', ''], required_words=['what', 'database']) response(long.R_BIT, ['what', 'is', 'a', 'bit'], required_words=['what', 'bit', 'bits']) response(long.R_SEC, ['what', 'is', 'security'], required_words=['what', 'security']) response(long.R_VIR, ['what', 'is', 'a', 'virus'], required_words=['what', 'virus']) response('Bye, have a nice day!', ['bye'], required_words=['bye']) response(long.R_FT, ['i am', 'im', 'fine', 'great', 'too'], required_words=['fine']) best_match = max(highest_prob_list, key=highest_prob_list.get) # print(highest_prob_list) return long.unknown() if highest_prob_list[best_match] < 1 else best_match
Прежде чем бот сможет понять сообщение, необходимо еще кое-что сделать с сообщением пользователя. В сообщении можно использовать знаки препинания. Они могут испортить программу, поэтому нам нужно их удалить. Это происходит в части split_message. Пока программа работает, пользователь может отправлять сообщения, отсюда и цикл while true.
def get_response(user_input): split_message = re.split(r'\s+|[,;?!.-]\s*', user_input.lower()) response = check_all_messages(split_message) return response # Testing the response system while True: print('Bot ' + get_response(input('You: ')) )
Теперь взглянем на второй файл, эта часть кода имеет две цели. Первый предназначен для длинных ответов. Вы можете разместить их здесь и сделать более длинные ответы для бота. Другая цель — когда бот не понимает пользователя, он скажет что-то вроде «что это значит?» или «не могли бы вы перефразировать это?».
import random R_EATING = "I don't like eating anything because I'm a bot obviously!" R_CS = "Computer science is the study of computation, automation and information." R_LANGUAGE = "There are many languages, like Python, JavaScript, Java, C#, C, C++, GO, R, Swift and PHP" R_POS = "There are lots of possibilities, like making your own site, making a app, making a database, the internet" R_AI = "AI is the simulation of human intelligence processes by machines, especially computer systems" R_VR = "VR is a simulated experience that employs pose tracking and 3D near-eye displays" R_WICS = "Parts of computer science are: technology, maths, management and applications" R_HW = "The machines, wiring and other physical components of a computer or other electronic system" R_SW = "The programs and other operating information used by a computer" R_ALG = "a process or set of rules to be followed in calculations or other problem-solving operations by a computer" R_DA = "A data structure is a specialized format for organizing, processing, retrieving and storing data" R_GRA = "Each language has his grammar, a computer must can execute the code" R_ARR = "Is a data structure that holds similar related data" R_DB = "A database is information that is set up for easy access, management and updating" R_BIT = "It is the smallest unit of information, it only has two values, yes/no, high/low or 1/0" R_SEC = "The protection of computer systems and information from harm, theft and unauthorized use" R_VIR = "A piece of code that is capable of copying itself and typically has a detrimental effect" R_FT = "Great! Do you have some question for me?" def unknown(): response = ['Could you please re-phrase that?', '...', 'What does that mean?'][random.randrange(3)] return response
Теперь самое интересное, тестирование и общение с ботом. Я прикреплю сюда скриншот, чтобы вы могли видеть, как шла беседа и какие были ответы бота.
Информатика — широкая тема со множеством интересных составляющих, и я всегда хотел сделать бота. Я нахожу захватывающим, как это работает. Я думаю, это действительно замечательно, что я смог сделать его сам. Конечно, это не идеально, и это невозможно, но я очень доволен конечным результатом.
Надеюсь, вам было интересно читать эту историю! Не забывайте подписываться на меня в Медиуме и, если хотите, читайте другие мои истории.