Advertisement
Mancolo

Untitled

May 10th, 2023
774
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.76 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.     key = dict()
  125.     for ec in counted_encoding_chars:
  126.         key[ec[0]] = None
  127.  
  128.     key[counted_encoding_chars[0][0]] = 'а'
  129.  
  130.     counted_encoding_chars_dict = dict(counted_encoding_chars)
  131.     counted_chars_dict = dict(counted_chars)
  132.     unknown_chars = ''.join([c[0] for c in counted_chars[2:]])
  133.     must_words = ["каныкей", 'деп', 'бейбак']
  134.     for word in must_words:
  135.         matches = find_words(encoded_words, create_pattern_signs(word, key, counted_encoding_chars))
  136.         # output.insert('end', f'{matches}')
  137.         if len(matches) == 1:
  138.             for i in range(len(word)):
  139.                 key[matches[0][i]] = word[i]
  140.  
  141.     while all(map(lambda x: x is not None, key.keys())):
  142.         # output.insert('end', f'{key}')
  143.         examples = []
  144.  
  145.         for word in encoded_words:
  146.             if check(word, key):
  147.                 reg = ''
  148.  
  149.                 for s in word:
  150.                     if key.get(s, None) is None:
  151.                         reg += f'[{get_chars(key)}]'
  152.                     else:
  153.                         reg += key[s]
  154.  
  155.                 reg += '$'
  156.  
  157.                 matches = find_words(sample_words, reg)
  158.                 # if word == 'лңк':
  159.                 #     print(matches, reg)
  160.                 matches = list(filter(lambda x: match_word(x, word), matches))
  161.  
  162.                 if len(matches) == 1 and any(map(lambda s: s not in key.values(), matches[0])):
  163.                     err = 0.0
  164.                     is_valid = True
  165.                     for i in range(len(matches[0])):
  166.                         if key[word[i]] is None:
  167.                             err += abs(
  168.                                 counted_encoding_chars_dict[word[i]] * 1.0 / counted_chars_dict[matches[0][i]] - 1)
  169.                             if matches[0][i] in list(key.values()):
  170.                                 is_valid = False
  171.                                 break
  172.                     if is_valid:
  173.                         examples.append((word, matches[0], err / len(word)))
  174.         if len(examples) == 0:
  175.             break
  176.         examples.sort(key=lambda x: x[2])
  177.         for i in range(len(examples[0][0])):
  178.             key[examples[0][0][i]] = examples[0][1][i]
  179.         # output.insert('end', f'{examples[0]}')
  180.  
  181.     text = ''
  182.  
  183.     for w in encoded_text:
  184.         w = w.lower()
  185.         if w.isalpha():
  186.             text += key[w] if key.get(w, None) is not None else 'X'
  187.         else:
  188.             text += w
  189.     output_text.insert('end', f'{text}')
  190.  
  191.  
  192. def display_func():
  193.     output = tk.Text(root, height=40, width=80)
  194.     output.pack()
  195.     my_func(output)
  196.  
  197.     # перенаправляем стандартный вывод в текстовый виджет
  198.     sys.stdout = output
  199.  
  200.     # вызываем функцию my_func
  201.     my_func()
  202.  
  203.     # возвращаем стандартный вывод на место
  204.     sys.stdout = sys.__stdout__
  205.  
  206. # текстовое поле для вывода
  207. output_text = tk.Text(root, height=20, width=80)
  208. output_text.pack()
  209.  
  210. # добавляем кнопку для дешифровки
  211. decrypt_button = tk.Button(root, text="Choose your file", command=my_func)
  212. decrypt_button.pack(pady=10)
  213.  
  214. # Запускаем главный цикл окна
  215. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement