Advertisement
ilyakanyshev

Untitled

Apr 17th, 2020
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.52 KB | None | 0 0
  1. import time
  2. from copy import copy
  3.  
  4.  
  5. # функция разделения текста на слова. Учитываются обращения от ВКонтача ([id1|Pavel Durov])
  6. def commandSplit(text):
  7.     results = [[""],[""]]
  8.     count = 1
  9.     countChars = 0
  10.     countSimvols = 0
  11.     for char in text:
  12.         countSimvols += 1
  13.         if char.lower() in 'qwertyuioplkjhgfdsazxcvbnmйцукенгшщзхъэждлорпавыфячсмитьбю':
  14.             countChars += 1
  15.         if count == 2:
  16.             if char == ']':
  17.                 count -= 1
  18.                 results[0][-1] += "]"
  19.                 results[0].append("")
  20.             else:
  21.                 results[0][-1] += char.lower()
  22.                 if char == " ":
  23.                     results[1].append("")
  24.                 else:
  25.                     results[1][-1] += char.lower()
  26.         else:
  27.             if char == "[":
  28.                 count += 1
  29.                 tmp = copy(results[0])
  30.                 tmp[-1] += char.lower()
  31.                 results[1] = tmp
  32.                 if results[0][-1] != "":
  33.                     results[0].append(char.lower())
  34.                 else:
  35.                     results[0][-1] += char.lower()
  36.             elif char == " ":
  37.                 results[0].append("")
  38.             else:
  39.                 results[0][-1] += char.lower()
  40.     results.append("")
  41.     return {
  42.         'countChars': countChars,
  43.         'countSimvols': countSimvols,
  44.         'result':  results[count-1],
  45.     }
  46.  
  47.  
  48. # Класс команды, ничего интересного
  49. class Command:
  50.     number = 0
  51.     index = 0
  52.     command = []
  53.     return_data = {}
  54.     return_value = ""
  55.     flag = True
  56.     def __init__(self, command, return_value):
  57.         self.command = []
  58.         self.return_data = {}
  59.         self.return_value = return_value
  60.         for _ in command:
  61.             if _ == "":
  62.                 continue
  63.             elif _[0]+_[-1] == "{}":
  64.                 if min([int(__ in 'qwertyuiopasdfghjklzxcvbnm') for __ in _[1:-1]]) == 1:
  65.                     self.return_data[_[1:-1]] = ""
  66.             self.command.append(_)
  67.             self.number += 1
  68.         self.command += ['']
  69.     def check(self, word):
  70.         if self.flag:
  71.             if self.number > self.index:
  72.                 if self.command[self.index] == "":
  73.                     self.flag = False
  74.                     return False
  75.                 if self.command[self.index] == "*":
  76.                     if self.command[self.index+1] == word:
  77.                         self.index += 2
  78.                 elif self.command[self.index] == word:
  79.                     self.index += 1
  80.                 elif self.command[self.index][0]+self.command[self.index][-1] == "{}":
  81.                     name = self.command[self.index][1:-1]
  82.                     if self.command[self.index + 1] == word:
  83.                         self.index += 2
  84.                     else:
  85.                         self.return_data[name] += word + " "
  86.                 else:
  87.                     self.flag = False
  88.                     return False
  89.                 return True
  90.         return False
  91.     def confirm(self):
  92.         return (self.flag and (self.number - self.index == 1))
  93.     def new(self):
  94.         try:
  95.             self.index = 0
  96.             for name in self.return_data.keys():
  97.                 self.return_data[name] = ""
  98.             self.flag = True
  99.             return True
  100.         except:
  101.             return False
  102.  
  103.  
  104. # Это команды, разделенные по словам. Первое слово - ключ функции, которая будет обрабатывать эту команду по передаваемым параметрам
  105. # В {} передаются названия переменных, передающихся в командах
  106. commands_splits = [
  107.     ['скажи', '{name}', 'скажи', '{text}',],
  108.     ['помощь', '{name}', 'помощь', '*',],
  109.     ['стата', '{name}', 'стата', '{user}',],
  110.     ['стата', '{name}', 'стат', '{user}',],
  111.     ['стата', '{name}', 'ливни', '{user}',],
  112.     ['пред', '{name}', 'пред', '{user}',],
  113.     ['кик', '{name}', 'кик', '{user}',],
  114.     ['команды', '{name}', 'команды',],
  115. ]
  116.  
  117.  
  118. # Создаем класс команды
  119. commands = []
  120. for command in commands_splits:
  121.     commands.append(Command(command[1:], command[0]))
  122.  
  123.  
  124. # Функция, которая определяет какой вариант команды ближе всего к исходной
  125. def test_function(command_words):
  126.     global commands
  127.     for _ in commands:
  128.         _.new()
  129.     for word in command_words:
  130.         for command in commands:
  131.             command.check(word)
  132.     true_command = []
  133.     for command in commands:
  134.         if command.confirm():
  135.             true_command.append({'value': command.return_value, 'return_data': command.return_data})
  136.     return true_command
  137.    
  138.  
  139. # Это тесты
  140. tests = [
  141.     'рая скажи пенис',
  142.     'рая скажи '+"["*4000,
  143.     'рая скажи лол.',
  144.     'рая скажи',
  145.     'рая скажи йцу',
  146.     'рая помощь',
  147.     'рая команды',
  148.     'рая стат [id1|Pavel Durov]',
  149.     'рая стат',
  150.     'кик',
  151.     'пред',
  152.     'стата',
  153.     'торч стата',
  154.     'сука бля стата',
  155. ]
  156.  
  157. class User:
  158.     id = 0
  159.     name = ""
  160.     flag = True
  161.     def __init__(self, string):
  162.         string = string.split("|")
  163.         string = string[0].split("[")[1]+string[1].split("]")[:-1]
  164.         self.id = string[0]
  165.         self.flag = False
  166.         if (string[0].isdigits())or(string[0][0]=="-")and(string[0][1:].isdigits()):
  167.             if len(string[0])>0:
  168.                 self.id = int(string[0])
  169.                 sef.flag = True
  170.         self.name = " ".join(_ for _ in string[1:])
  171.         if len(self.name)==0:
  172.             self.flag = False
  173.     def valid(self):
  174.         return self.flag
  175.  
  176.  
  177. # Тестирвоание функций на тестах
  178. for number, test in enumerate(tests):
  179.     n = 10**6
  180.     print("Test#{number}".format(number=number+1))
  181.     print("",test)
  182.     start_time = time.time()
  183.     cmd = commandSplit(test)
  184.     print(" Split results:", cmd)
  185.     print(" Split time:", str(int(n*(time.time()-start_time))/n)+"c.")
  186.     start_time = time.time()
  187.     return_data = test_function(cmd['result'])
  188.     print(" {value}".format(value=return_data))
  189.     print(" Time: ", str(int(n*(time.time()-start_time))/n)+"c.")
  190.     print("-"*24+"\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement