Advertisement
Mancolo

Untitled

May 11th, 2023
888
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.15 KB | None | 0 0
  1. import re
  2. from collections import defaultdict, Counter
  3. from typing import Dict, List
  4.  
  5.  
  6. def create_symbols(word):
  7.     return ''.join(filter(str.isalpha, word))
  8.  
  9.  
  10. def match_words(words: list, reg: str) -> list:
  11.     return [w for w in words if re.match(reg, w)]
  12.  
  13.  
  14. def count_words(text: str) -> tuple:
  15.     words = [create_symbols(w) for w in text.lower().split()]
  16.     word_dict = defaultdict(lambda: defaultdict(int))
  17.     tot = len(words)
  18.     for word in words:
  19.         word_dict[len(word)][word] += 1
  20.  
  21.     for k, words_same_size in word_dict.items():
  22.         for j, count in words_same_size.items():
  23.             word_dict[k][j] = count / (tot * 0.01)
  24.  
  25.         word_dict[k] = sorted(word_dict[k].items(), key=lambda x: -x[1])
  26.  
  27.     return word_dict, set(words)
  28.  
  29.  
  30. def count_chars(s: str) -> list:
  31.     s = s.lower()
  32.     d = Counter(filter(str.isalpha, s))
  33.     tot = sum(d.values())
  34.  
  35.     for k, v in d.items():
  36.         d[k] = v / (tot * 0.01)
  37.  
  38.     return sorted(d.items(), key=lambda x: -x[1])
  39.  
  40.  
  41. def is_checkable(word: str, key: Dict[str, str]) -> bool:
  42.     return any(key[k] is not None and k in word for k in key)
  43.  
  44.  
  45. def get_unknown_chars(key: Dict[str, str]) -> str:
  46.     alph = 'абвгдеёжзийклмнопрстуфчцчшщъыьэюяңөү'
  47.     return ''.join(c for c in alph if c not in key.values())
  48.  
  49.  
  50. def get_unknown_keys(key: Dict[str, str]) -> str:
  51.     return ''.join(c for c in key if key[c] is None)
  52.  
  53.  
  54. def check_pattern(match: str, word: str) -> bool:
  55.     return all((match[i] == match[j]) == (word[i] == word[j]) for i in range(len(word) - 1) for j in range(i, len(word)))
  56.  
  57.  
  58. def generate_pattern(word: str, key: Dict[str, str], counted_encoding_chars: List[List[str]]) -> str:
  59.     reg = ''
  60.     for s in word:
  61.         if s in key.values():
  62.             reg += list(key.keys())[list(key.values()).index(s)]
  63.         elif s in 'нкы':
  64.             reg += f'[{"".join(c[0] for c in counted_encoding_chars[1:4])}]'
  65.         else:
  66.             reg += f'[{get_unknown_keys(key)}]'
  67.  
  68.     return reg + '$'
  69.  
  70.  
  71. def test():
  72.     print("TEST")
  73.     return "Bye!!!!"
  74.  
  75.  
  76. def main():
  77.     encoded_text = open('D:/Codes/hwPy/teory/text.txt', 'r', encoding='UTF-8').read()
  78.     sample_text = open('D:/Codes/hwPy/teory/Manas-eposu-2010-S-Karalaev.txt', 'r', encoding='UTF-8').read().replace(
  79.         'www.el-sozduk.kg', '')
  80.  
  81.     counted_chars = count_chars(sample_text)
  82.     counted_encoding_chars = count_chars(encoded_text)
  83.  
  84.     _, encoded_words = count_words(encoded_text)
  85.     _, sample_words = count_words(sample_text)
  86.  
  87.     key = dict()
  88.     for ec in counted_encoding_chars:
  89.         key[ec[0]] = None
  90.  
  91.     key[counted_encoding_chars[0][0]] = 'а'
  92.     while True:
  93.         # тут я запрашиваю на который нужно заменить выбранный символ
  94.         print(key)
  95.  
  96.         char_to_replace = input("Введите символ, который нужно заменить (или нажмите Enter для выхода): ")
  97.  
  98.         if not char_to_replace:
  99.             break
  100.  
  101.         if char_to_replace in key:
  102.             # запрашиваем у пользователя символ, на который нужно заменить выбранный символ
  103.             new_char = input(f"Введите новое значение для символа '{char_to_replace}': ")
  104.  
  105.             # проверяем, есть ли другой символ в ключе, который также нужно заменить на новое значение
  106.             for k, v in key.items():
  107.                 if v == new_char and k != char_to_replace:
  108.                     print(f"Символ '{k}' также был заменен на '{new_char}'.")
  109.                     key[k] = None
  110.  
  111.             # обновляем словарь, если новое значение не равно None
  112.             if new_char != 'None':
  113.                 key[char_to_replace] = new_char
  114.         else:
  115.             print(f"Символ '{char_to_replace}' не найден в ключе.")
  116.  
  117.     counted_encoding_chars_dict = dict(counted_encoding_chars)
  118.     counted_chars_dict = dict(counted_chars)
  119.  
  120.     print(counted_chars)
  121.     print(counted_encoding_chars)
  122.  
  123.     unknown_chars = ''.join([c[0] for c in counted_chars[2:]])
  124.  
  125.     print(unknown_chars)
  126.  
  127.     # print(key)
  128.  
  129.     # bias = 0.05
  130.  
  131.     must_words = ["каныкей", 'деп', 'бейбак']
  132.  
  133.     for word in must_words:
  134.         matches = match_words(encoded_words, generate_pattern(word, key, counted_encoding_chars))
  135.         if len(matches) == 1:
  136.             for i, char in enumerate(word):
  137.                 key[matches[0][i]] = char
  138.  
  139.     while all(map(lambda x: x is not None, key.keys())):
  140.         print(key)
  141.  
  142. #здесь обновление ключа
  143.         # new_values = {}
  144.         # for k in key.keys():
  145.         #     if key[k] is None:
  146.         #         new_val = input(f"Введите новое значение для символа {k}: ")
  147.         #         new_values[k] = new_val
  148.         #
  149.         # key.update(new_values)
  150.  
  151.         examples = []
  152.  
  153.         for word in encoded_words:
  154.             if is_checkable(word, key):
  155.                 reg = ''
  156.  
  157.                 for s in word:
  158.                     if key.get(s, None) is None:
  159.                         reg += f'[{get_unknown_chars(key)}]'
  160.                     else:
  161.                         reg += key[s]
  162.  
  163.                 reg += '$'
  164.  
  165.                 # print(word, reg)
  166.  
  167.                 matches = match_words(sample_words, reg)
  168.                 if word == 'лңк':
  169.                     print(matches, reg)
  170.                 matches = list(filter(lambda x: check_pattern(x, word), matches))
  171.  
  172.                 # if matches:
  173.                 #     print(matches)
  174.  
  175.                 if len(matches) == 1 and any(map(lambda s: s not in key.values(), matches[0])):
  176.                     # print(matches[0])
  177.                     err = 0.0
  178.                     is_valid = True
  179.  
  180.                     for i in range(len(matches[0])):
  181.                         if key[word[i]] is None:
  182.                             err += abs(
  183.                                 counted_encoding_chars_dict[word[i]] * 1.0 / counted_chars_dict[matches[0][i]] - 1)
  184.  
  185.                             if matches[0][i] in list(key.values()):
  186.                                 is_valid = False
  187.                                 break
  188.  
  189.                     if is_valid:
  190.                         examples.append((word, matches[0], err / len(word)))
  191.  
  192.         if len(examples) == 0:
  193.             break
  194.  
  195.         examples.sort(key=lambda x: x[2])
  196.  
  197.         for i in range(len(examples[0][0])):
  198.             key[examples[0][0][i]] = examples[0][1][i]
  199.  
  200.         print(examples[0])
  201.  
  202.     text = ''
  203.  
  204.     for w in encoded_text:
  205.         w = w.lower()
  206.         if w.isalpha():
  207.             text += key[w] if key.get(w, None) is not None else 'X'
  208.         else:
  209.             text += w
  210.  
  211.     # print(''.join([k for k in key.values() if k is not None]))
  212.     # print(''.join([k for k in key.keys() if key[k] is not None]))
  213.     print(text)
  214.     # print(key)
  215.     # print(sample_words)
  216.  
  217.     # print(list(key.values()).count(None))
  218.  
  219.  
  220. print(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement