Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- from copy import copy
- # функция разделения текста на слова. Учитываются обращения от ВКонтача ([id1|Pavel Durov])
- def commandSplit(text):
- results = [[""],[""]]
- count = 1
- countChars = 0
- countSimvols = 0
- for char in text:
- countSimvols += 1
- if char.lower() in 'qwertyuioplkjhgfdsazxcvbnmйцукенгшщзхъэждлорпавыфячсмитьбю':
- countChars += 1
- if count == 2:
- if char == ']':
- count -= 1
- results[0][-1] += "]"
- results[0].append("")
- else:
- results[0][-1] += char.lower()
- if char == " ":
- results[1].append("")
- else:
- results[1][-1] += char.lower()
- else:
- if char == "[":
- count += 1
- tmp = copy(results[0])
- tmp[-1] += char.lower()
- results[1] = tmp
- if results[0][-1] != "":
- results[0].append(char.lower())
- else:
- results[0][-1] += char.lower()
- elif char == " ":
- results[0].append("")
- else:
- results[0][-1] += char.lower()
- results.append("")
- return {
- 'countChars': countChars,
- 'countSimvols': countSimvols,
- 'result': results[count-1],
- }
- # Класс команды, ничего интересного
- class Command:
- number = 0
- index = 0
- command = []
- return_data = {}
- return_value = ""
- flag = True
- def __init__(self, command, return_value):
- self.command = []
- self.return_data = {}
- self.return_value = return_value
- for _ in command:
- if _ == "":
- continue
- elif _[0]+_[-1] == "{}":
- if min([int(__ in 'qwertyuiopasdfghjklzxcvbnm') for __ in _[1:-1]]) == 1:
- self.return_data[_[1:-1]] = ""
- self.command.append(_)
- self.number += 1
- self.command += ['']
- def check(self, word):
- if self.flag:
- if self.number > self.index:
- if self.command[self.index] == "":
- self.flag = False
- return False
- if self.command[self.index] == "*":
- if self.command[self.index+1] == word:
- self.index += 2
- elif self.command[self.index] == word:
- self.index += 1
- elif self.command[self.index][0]+self.command[self.index][-1] == "{}":
- name = self.command[self.index][1:-1]
- if self.command[self.index + 1] == word:
- self.index += 2
- else:
- self.return_data[name] += word + " "
- else:
- self.flag = False
- return False
- return True
- return False
- def confirm(self):
- return (self.flag and (self.number - self.index == 1))
- def new(self):
- try:
- self.index = 0
- for name in self.return_data.keys():
- self.return_data[name] = ""
- self.flag = True
- return True
- except:
- return False
- # Это команды, разделенные по словам. Первое слово - ключ функции, которая будет обрабатывать эту команду по передаваемым параметрам
- # В {} передаются названия переменных, передающихся в командах
- commands_splits = [
- ['скажи', '{name}', 'скажи', '{text}',],
- ['помощь', '{name}', 'помощь', '*',],
- ['стата', '{name}', 'стата', '{user}',],
- ['стата', '{name}', 'стат', '{user}',],
- ['стата', '{name}', 'ливни', '{user}',],
- ['пред', '{name}', 'пред', '{user}',],
- ['кик', '{name}', 'кик', '{user}',],
- ['команды', '{name}', 'команды',],
- ]
- # Создаем класс команды
- commands = []
- for command in commands_splits:
- commands.append(Command(command[1:], command[0]))
- # Функция, которая определяет какой вариант команды ближе всего к исходной
- def test_function(command_words):
- global commands
- for _ in commands:
- _.new()
- for word in command_words:
- for command in commands:
- command.check(word)
- true_command = []
- for command in commands:
- if command.confirm():
- true_command.append({'value': command.return_value, 'return_data': command.return_data})
- return true_command
- # Это тесты
- tests = [
- 'рая скажи пенис',
- 'рая скажи '+"["*4000,
- 'рая скажи лол.',
- 'рая скажи',
- 'рая скажи йцу',
- 'рая помощь',
- 'рая команды',
- 'рая стат [id1|Pavel Durov]',
- 'рая стат',
- 'кик',
- 'пред',
- 'стата',
- 'торч стата',
- 'сука бля стата',
- ]
- class User:
- id = 0
- name = ""
- flag = True
- def __init__(self, string):
- string = string.split("|")
- string = string[0].split("[")[1]+string[1].split("]")[:-1]
- self.id = string[0]
- self.flag = False
- if (string[0].isdigits())or(string[0][0]=="-")and(string[0][1:].isdigits()):
- if len(string[0])>0:
- self.id = int(string[0])
- sef.flag = True
- self.name = " ".join(_ for _ in string[1:])
- if len(self.name)==0:
- self.flag = False
- def valid(self):
- return self.flag
- # Тестирвоание функций на тестах
- for number, test in enumerate(tests):
- n = 10**6
- print("Test#{number}".format(number=number+1))
- print("",test)
- start_time = time.time()
- cmd = commandSplit(test)
- print(" Split results:", cmd)
- print(" Split time:", str(int(n*(time.time()-start_time))/n)+"c.")
- start_time = time.time()
- return_data = test_function(cmd['result'])
- print(" {value}".format(value=return_data))
- print(" Time: ", str(int(n*(time.time()-start_time))/n)+"c.")
- print("-"*24+"\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement