Advertisement
Mancolo

Untitled

May 10th, 2023
674
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.45 KB | None | 0 0
  1. import tkinter as tk
  2. from tkinter import filedialog
  3. import re
  4. from typing import Dict
  5. import sys
  6.  
  7. # Создаем корневое окно
  8. root = tk.Tk()
  9. root.title("Decoder")
  10. # root.geometry('600x500')
  11. # root.resizable(width=False, height=False)
  12.  
  13. text1 = tk.Text(root)
  14. text1.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
  15.  
  16. # Создаем полосу прокрутки
  17. scrollbar = tk.Scrollbar(root)
  18. scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
  19.  
  20. # Привязываем полосу прокрутки к текстовому виджету
  21. text1.config(yscrollcommand=scrollbar.set)
  22. scrollbar.config(command=text1.yview)
  23.  
  24.  
  25. def create_symbols(s: str) -> list:
  26.     s = s.lower()
  27.     d = {}
  28.     tot = 0
  29.     for c in s:
  30.         if c.isalpha() and c not in "quote":
  31.             d[c] = d.get(c, 0) + 1
  32.             tot += 1
  33.  
  34.     for k in d:
  35.         d[k] /= tot * 0.01
  36.  
  37.     si = list(d.items())
  38.     si.sort(key=lambda x: -x[1])
  39.  
  40.     return si
  41.  
  42.  
  43. def check_word(word):
  44.     return ''.join(i for i in word if i.isalpha())
  45.  
  46.  
  47. def match_word(match: str, word: str) -> bool:
  48.     return all(
  49.         (match[i] == match[j]) == (word[i] == word[j]) for i in range(len(word) - 1) for j in range(i, len(word)))
  50.  
  51.  
  52. def count_words(text: str) -> tuple:
  53.     words = [check_word(w) for w in text.lower().split()]
  54.     word_dict = {}
  55.     tot = 0
  56.     for word in words:
  57.         words_same_size = word_dict.setdefault(len(word), {})
  58.         words_same_size[word] = words_same_size.get(word, 0) + 1
  59.         tot += 1
  60.  
  61.         word_dict[len(word)] = words_same_size
  62.  
  63.     for k in word_dict:
  64.         for j in word_dict[k]:
  65.             word_dict[k][j] /= tot * 0.01
  66.  
  67.     for k in word_dict:
  68.         si = list(word_dict[k].items())
  69.         si.sort(key=lambda x: -x[1])
  70.         word_dict[k] = si
  71.  
  72.     return word_dict, set(words)
  73.  
  74.  
  75. def find_words(words: list, reg: str) -> list:
  76.     return [w for w in words if re.match(reg, w)]
  77.  
  78.  
  79. def check(word: str, key: Dict) -> bool:
  80.     return any(key[k] is not None and k in word for k in key)
  81.  
  82.  
  83. def get_keys(key: Dict) -> str:
  84.     return ''.join(c for c in key if key[c] is None)
  85.  
  86.  
  87. def get_chars(key: Dict):
  88.     alph = 'абвгдеёжзийклмнопрстуфчцчшщъыьэюяңөү'
  89.     return ''.join((c for c in alph if c not in key.values()))
  90.  
  91.  
  92. def create_pattern_signs(word, key, counted_encoding_chars):
  93.     reg = ''
  94.     for s in word:
  95.         if s in key.values():
  96.             reg += list(key.keys())[list(key.values()).index(s)]
  97.         elif s in 'нкы':
  98.             reg += f'[{"".join(c[0] for c in counted_encoding_chars[1:4])}]'
  99.         else:
  100.             reg += f'[{get_keys(key)}]'
  101.     return reg + '$'
  102.  
  103.  
  104. def my_func():
  105.     file_path = filedialog.askopenfilename(
  106.         filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
  107.     )
  108.     if file_path:
  109.         with open(file_path, "r", encoding='utf-8') as file:
  110.             content = file.read()
  111.             # Добавляем содержимое файла в текстовый виджет
  112.             text1.delete("1.0", tk.END)
  113.             text1.insert(tk.END, content)
  114.     encoded_text = open(file_path, 'r', encoding='UTF-8').read()
  115.     sample_text = open('D:/Codes/hwPy/teory/Manas-eposu-2010-S-Karalaev.txt', 'r', encoding='UTF-8').read().replace(
  116.         'www.el-sozduk.kg', '')
  117.  
  118.     counted_chars = create_symbols(sample_text)
  119.     counted_encoding_chars = create_symbols(encoded_text)
  120.  
  121.     _, encoded_words = count_words(encoded_text)
  122.     _, sample_words = count_words(sample_text)
  123.  
  124.     # инициализация словаря ключей
  125.     key = {char[0]: None for char in counted_encoding_chars}
  126.     key[counted_encoding_chars[0][0]] = 'а'
  127.  
  128.     counted_encoding_chars_dict = dict(counted_encoding_chars)
  129.     counted_chars_dict = dict(counted_chars)
  130.  
  131.     # обновление словаря ключей на основе обязательных слов
  132.     must_words = ["каныкей", 'деп', 'бейбак']
  133.     for word in must_words:
  134.         pattern = create_pattern_signs(word, key, counted_encoding_chars)
  135.         matches = find_words(encoded_words, pattern)
  136.         if len(matches) == 1:
  137.             for i, char in enumerate(matches[0]):
  138.                 if key[char] is None:
  139.                     key[char] = word[i]
  140.  
  141.     # обновление словаря ключей на основе анализа закодированного текста
  142.     while None in key.values():
  143.         examples = []
  144.         for word in encoded_words:
  145.             if not check(word, key):
  146.                 continue
  147.             pattern = ''.join([f'[{get_chars(key)}]' if key.get(s) is None else key[s] for s in word]) + '$'
  148.             matches = [match for match in (find_words(sample_words, pattern)) if match_word(match, word)]
  149.             matches = [match for match in matches if any([s not in key.values() for s in match])]
  150.             if len(matches) == 1:
  151.                 err = sum(
  152.                     [abs(counted_encoding_chars_dict[word[i]] * 1.0 / counted_chars_dict[matches[0][i]] - 1) for i in
  153.                      range(len(matches[0])) if key[word[i]] is None]) / len(word)
  154.                 examples.append((word, matches[0], err))
  155.  
  156.         if not examples:
  157.             break
  158.         examples.sort(key=lambda x: x[2])
  159.         for i, char in enumerate(examples[0][0]):
  160.             if key[char] is None and examples[0][1][i] not in key.values():
  161.                 key[char] = examples[0][1][i]
  162.  
  163.     text = ''
  164.     for w in encoded_text:
  165.         w = w.lower()
  166.         if w.isalpha():
  167.             text += key[w] if key.get(w, None) is not None else 'X'
  168.         else:
  169.             text += w
  170.     output_text.insert('end', f'{text}')
  171.  
  172.  
  173. def display_func():
  174.     output = tk.Text(root, height=40, width=80)
  175.     output.pack()
  176.     my_func(output)
  177.  
  178.     # перенаправляем стандартный вывод в текстовый виджет
  179.     sys.stdout = output
  180.  
  181.     # вызываем функцию my_func
  182.     my_func()
  183.  
  184.     # возвращаем стандартный вывод на место
  185.     sys.stdout = sys.__stdout__
  186.  
  187. # текстовое поле для вывода
  188. output_text = tk.Text(root, height=20, width=80)
  189. output_text.pack()
  190.  
  191. # добавляем кнопку для дешифровки
  192. decrypt_button = tk.Button(root, text="Choose your file", command=my_func)
  193. decrypt_button.pack(pady=10)
  194.  
  195. # Запускаем главный цикл окна
  196. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement