program_efremova.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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():
  11. file = Path(dictionary_filename)
  12. if not file.is_file():
  13. print('Файл {} не существует. Программа не может быть выполнена'.format(dictionary_filename))
  14. return
  15. func()
  16. return wrapper
  17. def if_exist_json(func):
  18. def wrapper():
  19. file = Path(json_filename)
  20. if not file.is_file():
  21. print('Файл {} не существует. Его нужно сгенерировать первоначально'.format(json_filename))
  22. return
  23. func()
  24. return wrapper
  25. def function_execution_time(func):
  26. def wrapper():
  27. start = time.time()
  28. func()
  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. split_line = line.split(' ', 1)
  63. word = split_line[0]
  64. definition = split_line[1]
  65. if not bool(re.match(r'(ж|м|ср|мн)\.(.*)$', definition) or re.match(r'(1\.|I) (ж|м|ср|мн)\.(.*)$', definition)):
  66. continue
  67. is_probably_not_noun = False
  68. endings = ['ая', 'ее', 'ие', 'ий', 'ое', 'ой', 'ые', 'ый', 'ье', 'ьи', 'ья', 'яя']
  69. for ending in endings:
  70. is_probably_not_noun = is_probably_not_noun or word.endswith(ending)
  71. dictionary[word] = {'definition': definition,
  72. 'is_probably_not_noun': is_probably_not_noun,
  73. 'answer_from_sites': 'null'}
  74. save_json(dictionary)
  75. @function_execution_time
  76. @if_exist_json
  77. def how_many_articles_need_to_check():
  78. dictionary = read_json()
  79. count_all = 0
  80. count_nouns_by_dictionary = 0
  81. count_check = 0
  82. for word, entry in dictionary.items():
  83. count_all += 1
  84. if entry['is_noun_by_dictionary']:
  85. count_nouns_by_dictionary += 1
  86. if (
  87. entry['is_noun_by_dictionary'] and
  88. entry['is_probably_not_noun'] and
  89. entry['answer_from_sites'] == 'null'
  90. ):
  91. count_check += 1
  92. print('Все слова: {}'.format(count_all))
  93. print('Количество существительных по Ефремовой: {}'.format(count_nouns_by_dictionary))
  94. print('Нужно проверить на сайтах: {}'.format(count_check))
  95. @function_execution_time
  96. @if_exist_json
  97. def print_list_of_words(answer_from_sites):
  98. dictionary = read_json()
  99. count = 0
  100. for word, entry in dictionary.items():
  101. if entry['is_noun_by_dictionary'] and entry['is_probably_not_noun']:
  102. is_print = False
  103. if answer_from_sites == 'null' and entry['answer_from_sites'] == 'null':
  104. is_print = True
  105. if answer_from_sites == '404' and entry['answer_from_sites'] == 404:
  106. is_print = True
  107. if is_print:
  108. print(word)
  109. print('answer_from_sites = {}'.format(entry['answer_from_sites']))
  110. print('-------------------------')
  111. count += 1
  112. print('Слов: {}'.format(count))
  113. @function_execution_time
  114. @if_exist_json
  115. def check_words_on_sites():
  116. dictionary = read_json()
  117. i = 0
  118. for word, entry in dictionary.items():
  119. if (
  120. entry['is_noun_by_dictionary'] and
  121. entry['is_probably_not_noun'] and
  122. entry['answer_from_sites'] == 'null'
  123. ):
  124. try:
  125. response = requests.get('https://ru.wiktionary.org/wiki/' + word)
  126. print('{} status_code = {}'.format(word, response.status_code))
  127. if response.status_code == 200:
  128. html = response.text
  129. is_noun_by_wiktionary = False
  130. is_not_noun_by_wiktionary = False
  131. if (
  132. 'title="существительное">Существительное</a>' in html or
  133. 'Существительное.' in html or
  134. 'title="выступает в роли существительного">субстантивир.</span>' in html or
  135. ('Существительное' in html and 'Прилагательное' not in html) or
  136. 'Существительное, одушевлённое, тип склонения по ' in html
  137. ):
  138. is_noun_by_wiktionary = True
  139. if (
  140. 'title="прилагательное">Прилагательное</a>' in html or
  141. 'title="причастие">Причастие</a>' in html or
  142. 'title="причастие">причастие</a>' in html or
  143. 'title="наречие">Наречие</a>' in html or
  144. 'title="деепричастие">деепричастие</a>' in html or
  145. ('Существительное' not in html and 'Прилагательное' in html) or
  146. ('Существительное' not in html and 'прилагательного' in html) or
  147. ('Существительное' not in html and 'Местоименное прилагательное' in html) or
  148. ('Существительное' not in html and 'Притяжательное местоимение' in html) or
  149. ('Существительное' not in html and 'Притяжательное прилагательное' in html) or
  150. ('Существительное' not in html and 'Числительное' in html) or
  151. ('Существительное' not in html and 'Порядковое числительное' in html) or
  152. ('Существительное' not in html and 'Местоимение' in html) or
  153. ('Существительное' not in html and 'Указательное местоимение' in html)
  154. ):
  155. is_not_noun_by_wiktionary = True
  156. if is_noun_by_wiktionary:
  157. dictionary[word]['answer_from_sites'] = 'noun'
  158. print('answer_from_sites = noun')
  159. if is_not_noun_by_wiktionary:
  160. dictionary[word]['answer_from_sites'] = 'not_noun'
  161. print('answer_from_sites = not_noun')
  162. if not is_noun_by_wiktionary and not is_not_noun_by_wiktionary:
  163. print('Need more checks')
  164. else:
  165. dictionary[word]['answer_from_sites'] = response.status_code
  166. print('url = {}'.format(response.url))
  167. print('-------------------------')
  168. i += 1
  169. if i % 100 == 0:
  170. save_json(dictionary)
  171. except ConnectionError:
  172. print("Error: ConnectionError")
  173. time.sleep(1)
  174. i = 0
  175. for word, entry in dictionary.items():
  176. if (
  177. entry['is_noun_by_dictionary'] and
  178. entry['is_probably_not_noun'] and
  179. entry['answer_from_sites'] == 404
  180. ):
  181. try:
  182. response = requests.get('https://dic.academic.ru/searchall.php?SWord=' + word)
  183. print('{} status_code = {}'.format(word, response.status_code))
  184. if response.status_code == 200:
  185. html = response.text
  186. is_noun_by_wiktionary = False
  187. is_not_noun_by_wiktionary = False
  188. if re.search(
  189. re.escape(
  190. word) + r'</a><\/strong> — сущ\.(.*?)<\/p>\n<p class="src"><a href="\/\/dic\.academic\.ru\/contents.nsf\/dic_synonims\/">Словарь синонимов<\/a><\/p>',
  191. html, re.S):
  192. is_noun_by_wiktionary = True
  193. if is_noun_by_wiktionary:
  194. dictionary[word]['answer_from_sites'] = 'noun'
  195. print('answer_from_sites = noun')
  196. # if is_not_noun_by_wiktionary:
  197. # dictionary[word]['answer_from_sites'] = 'not_noun'
  198. # print('answer_from_sites = not_noun')
  199. if not is_noun_by_wiktionary:
  200. print('Need more checks')
  201. print('-------------------------')
  202. i += 1
  203. if i % 100 == 0:
  204. save_json(dictionary)
  205. except ConnectionError:
  206. print("Ошибка: ConnectionError")
  207. time.sleep(1)
  208. save_json(dictionary)
  209. print('Проверка подозрительных слов завершена')
  210. @if_exist_dictionary
  211. def main():
  212. menu = [
  213. {'text': 'Очистить временные файлы', 'function': remove_all_temporary_files},
  214. {'text': 'Сгенерировать файл {}'.format(json_filename), 'function': generated_json},
  215. {'text': 'Сколько слов нужно проверить на сайтах', 'function': how_many_articles_need_to_check},
  216. {'text': 'Вывести список непроверенных слов (answer_from_sites = null)',
  217. 'function': print_list_of_words, 'params': 'null'},
  218. {'text': 'Вывести список непроверенных слов c ошибкой 404 (answer_from_sites = 404)',
  219. 'function': print_list_of_words, 'params': '404'},
  220. {'text': 'Проверить подозрительные слова на сайтах', 'function': check_words_on_sites}
  221. ]
  222. while True:
  223. for index, item in enumerate(menu):
  224. print('{} - {}'.format(index + 1, item['text']))
  225. command = int(input('Введите номер команды (любой другой номер завершит программу): '))
  226. if command > len(menu) or command < 0:
  227. break
  228. if 'params' not in menu[command - 1]:
  229. menu[command - 1]['function']()
  230. else:
  231. menu[command - 1]['function'](menu[command - 1]['params'])
  232. input("Нажмите Enter для продолжения...")
  233. def test():
  234. pass
  235. if __name__ == '__main__':
  236. main()