program_efremova.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. from pathlib import Path
  2. import json
  3. import re
  4. import requests
  5. import time
  6. import os
  7. dictionary_filename = 'efremova.txt'
  8. json_filename = 'data.json'
  9. def if_exist_dictionary(func):
  10. def wrapper(*original_args, **original_kwargs):
  11. file = Path(dictionary_filename)
  12. if not file.is_file():
  13. print('Файл {} не существует. Программа не может быть выполнена'.format(dictionary_filename))
  14. return
  15. func(*original_args, **original_kwargs)
  16. return wrapper
  17. def if_exist_json(func):
  18. def wrapper(*original_args, **original_kwargs):
  19. file = Path(json_filename)
  20. if not file.is_file():
  21. print('Файл {} не существует. Его нужно сгенерировать первоначально'.format(json_filename))
  22. return
  23. func(*original_args, **original_kwargs)
  24. return wrapper
  25. def function_execution_time(func):
  26. def wrapper(*original_args, **original_kwargs):
  27. start = time.time()
  28. func(*original_args, **original_kwargs)
  29. end = time.time()
  30. print('Время выполнения функции: {}\n'.format(time.strftime('%H:%M:%S', time.gmtime(end - start))))
  31. return wrapper
  32. def save_json(dictionary):
  33. file = Path(json_filename)
  34. action = 'обновлен' if file.is_file() else 'создан'
  35. with open(json_filename, 'w', encoding='utf8') as outfile:
  36. json.dump(dictionary, outfile, ensure_ascii=False, indent=4)
  37. print('Файл {} {}'.format(json_filename, action))
  38. def read_json():
  39. file = Path(json_filename)
  40. with open(file, encoding='utf8') as f:
  41. dictionary = json.loads(f.read())
  42. print('Файл {} открыт'.format(json_filename))
  43. return dictionary
  44. @function_execution_time
  45. def remove_all_temporary_files():
  46. def remove(filename):
  47. if Path(json_filename).is_file():
  48. os.remove(json_filename)
  49. print('Файл {} удален'.format(json_filename))
  50. else:
  51. print('Файл {} не существует'.format(json_filename))
  52. remove(json_filename)
  53. print('Временных файлов больше нет')
  54. @function_execution_time
  55. @if_exist_dictionary
  56. def generated_json():
  57. file = Path(dictionary_filename)
  58. with open(file, encoding='utf8') as f:
  59. lines = f.read().splitlines()
  60. dictionary = {}
  61. for line in lines:
  62. word = line.split(' ', 1)[0]
  63. definition = line.split(' ', 1)[1]
  64. if not bool(re.match(r'(ж|м|ср|мн)\.(.*)$', definition) or re.match(r'(1\.|I) (ж|м|ср|мн)\.(.*)$', definition)):
  65. continue
  66. dictionary[word] = {'definition': definition}
  67. if word[-2:] in ['ая', 'ее', 'ие', 'ий', 'ое', 'ой', 'ые', 'ый', 'ье', 'ьи', 'ья', 'яя']:
  68. dictionary[word]['answerIsProbablyNotNoun'] = 'null'
  69. if bool(re.match(r'(мн)\.(.*)$', definition) or re.match(r'(1\.|I) (мн)\.(.*)$', definition)):
  70. dictionary[word]['answerNeedToIncludePlural'] = 'null'
  71. save_json(dictionary)
  72. @function_execution_time
  73. @if_exist_json
  74. def statistics():
  75. dictionary = read_json()
  76. count = 0
  77. count_check = 0
  78. count_need_check = 0
  79. count_plural_check = 0
  80. count_plural_need_check = 0
  81. for word, entry in dictionary.items():
  82. count += 1
  83. if 'answerIsProbablyNotNoun' in entry:
  84. count_check += 1
  85. if entry['answerIsProbablyNotNoun'] == 'null':
  86. count_need_check += 1
  87. if 'answerNeedToIncludePlural' in entry:
  88. count_plural_check += 1
  89. if entry['answerNeedToIncludePlural'] == 'null':
  90. count_plural_need_check += 1
  91. print('Всего существительных по Ефремовой: {}'.format(count))
  92. print('Подозрительные (возможно не сущ.):')
  93. print('\tвсего: {}'.format(count_check))
  94. print('\tнужно проверить: {}'.format(count_need_check))
  95. print('\tпроверено: {}'.format(count_check - count_need_check))
  96. print('Слова во множественном числе по Ефремовой:')
  97. print('\tвсего: {}'.format(count_plural_check))
  98. print('\tнужно проверить: {}'.format(count_plural_need_check))
  99. print('\tпроверено: {}'.format(count_plural_check - count_plural_need_check))
  100. @function_execution_time
  101. @if_exist_json
  102. def print_list_of_words(key, answer):
  103. def print_word():
  104. print(word)
  105. print('{} = {}'.format(key, entry[key]))
  106. print('-------------------------')
  107. dictionary = read_json()
  108. count = 0
  109. for word, entry in dictionary.items():
  110. if key in entry:
  111. if entry[key] == answer:
  112. print_word()
  113. count += 1
  114. print('Слов: {}'.format(count))
  115. def check_word_in_wiktionary(word, html):
  116. answer = None
  117. if '<title>{} — Викисловарь</title>'.format(word) not in html:
  118. return '404';
  119. if 'title="существительное">Существительное</a>' in html:
  120. answer = 'noun'
  121. if 'Существительное.' in html:
  122. answer = 'noun'
  123. if 'title="выступает в роли существительного">субстантивир.</span>' in html:
  124. answer = 'noun'
  125. if 'Существительное' in html and 'Прилагательное' not in html:
  126. answer = 'noun'
  127. if 'Существительное, одушевлённое, тип склонения по ' in html:
  128. answer = 'noun'
  129. if 'title="прилагательное">Прилагательное</a>' in html:
  130. answer = 'not noun'
  131. if 'title="причастие">Причастие</a>' in html:
  132. answer = 'not noun'
  133. if 'title="причастие">причастие</a>' in html:
  134. answer = 'not noun'
  135. if 'title="наречие">Наречие</a>' in html:
  136. answer = 'not noun'
  137. if 'title="деепричастие">деепричастие</a>' in html:
  138. answer = 'not noun'
  139. if 'Существительное' not in html and 'Прилагательное' in html:
  140. answer = 'not noun'
  141. if 'Существительное' not in html and 'прилагательного' in html:
  142. answer = 'not noun'
  143. if 'Существительное' not in html and 'Местоименное прилагательное' in html:
  144. answer = 'not noun'
  145. if 'Существительное' not in html and 'Притяжательное местоимение' in html:
  146. answer = 'not noun'
  147. if 'Существительное' not in html and 'Притяжательное прилагательное' in html:
  148. answer = 'not noun'
  149. if 'Существительное' not in html and 'Числительное' in html:
  150. answer = 'not noun'
  151. if 'Существительное' not in html and 'Порядковое числительное' in html:
  152. answer = 'not noun'
  153. if 'Существительное' not in html and 'Местоимение' in html:
  154. answer = 'not noun'
  155. if 'Существительное' not in html and 'Указательное местоимение' in html:
  156. answer = 'not noun'
  157. return answer
  158. def check_word_in_academic(word, html):
  159. answer = None
  160. regexp = r'</a><\/strong> — сущ\.(.*?)<\/p>\n<p class="src">' \
  161. r'<a href="\/\/dic\.academic\.ru\/contents.nsf\/dic_synonims\/">Словарь синонимов<\/a><\/p>'
  162. if re.search(re.escape(word) + regexp, html, re.S):
  163. answer = 'noun'
  164. return answer
  165. def check_word_in_site(word, url, func_check_in_html):
  166. answer = None
  167. try:
  168. response = requests.get(url + word, allow_redirects=False)
  169. if response.status_code == 200:
  170. answer_from_html = func_check_in_html(word, response.text)
  171. if answer_from_html is not None:
  172. answer = answer_from_html
  173. else:
  174. answer = response.status_code
  175. except ConnectionError:
  176. print("Ошибка: ConnectionError")
  177. time.sleep(1)
  178. print('word = {}'.format(word))
  179. print('answer = {}'.format(answer))
  180. print('-------------------------')
  181. return answer
  182. @function_execution_time
  183. @if_exist_json
  184. def check_words_on_site(url, func_check_in_html):
  185. dictionary = read_json()
  186. i = 0
  187. for word, entry in dictionary.items():
  188. if 'answerIsProbablyNotNoun' in entry and entry['answerIsProbablyNotNoun'] == 'null':
  189. answer = check_word_in_site(word, url, func_check_in_html)
  190. if answer is not None:
  191. dictionary[word]['answerIsProbablyNotNoun'] = answer
  192. i += 1
  193. if i % 100 == 0:
  194. save_json(dictionary)
  195. save_json(dictionary)
  196. print('Проверка слов на {} завершена'.format(url))
  197. @if_exist_dictionary
  198. def main():
  199. menu = [
  200. {'text': 'Очистить временные файлы', 'function': remove_all_temporary_files},
  201. {'text': 'Сгенерировать файл {}'.format(json_filename), 'function': generated_json},
  202. {'text': 'Статистика', 'function': statistics},
  203. {'text': 'Список непроверенных подозрительных слов', 'function': print_list_of_words,
  204. 'params': {'key': 'answerIsProbablyNotNoun', 'answer': 'null'}},
  205. {'text': 'Список проверенных подозрительных слов с ошибкой 404', 'function': print_list_of_words,
  206. 'params': {'key': 'answerIsProbablyNotNoun', 'answer': '404'}},
  207. {'text': 'Список непроверенных слов во мн. числе', 'function': print_list_of_words,
  208. 'params': {'key': 'answerNeedToIncludePlural', 'answer': 'null'}},
  209. {'text': 'Проверить подозрительные слова на wiktionary.org', 'function': check_words_on_site,
  210. 'params': {'url': 'https://ru.wiktionary.org/wiki/', 'func_check_in_html': check_word_in_wiktionary}},
  211. {'text': 'Проверить подозрительные слова на dic.academic.ru', 'function': check_words_on_site,
  212. 'params': {'url': 'https://dic.academic.ru/searchall.php?SWord=',
  213. 'func_check_in_html': check_word_in_academic}}
  214. ]
  215. while True:
  216. for index, item in enumerate(menu):
  217. print('{} - {}'.format(index + 1, item['text']))
  218. try:
  219. command = int(input('Введите номер команды (нажмите Enter для выхода): '))
  220. except ValueError:
  221. break
  222. if command > len(menu) or command < 0:
  223. break
  224. if 'params' not in menu[command - 1]:
  225. menu[command - 1]['function']()
  226. else:
  227. menu[command - 1]['function'](**menu[command - 1]['params'])
  228. input("Нажмите Enter для продолжения...")
  229. def test():
  230. answer = check_word_in_site('мост', 'https://dic.academic.ru/searchall.php?SWord=', check_word_in_academic)
  231. print(answer)
  232. if __name__ == '__main__':
  233. main()