program_efremova.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. dictionary_json_filename = 'data.json'
  9. def main():
  10. if not is_exist_dictionary():
  11. return
  12. menu = {
  13. 1: {'text': 'Очистить временные файлы', 'function': clear_all_temporary_files},
  14. 2: {'text': 'Сгенерировать файл {}'.format(dictionary_json_filename), 'function': generated_json},
  15. 3: {'text': 'Сколько слов нужно проверить на сайтах', 'function': how_many_articles_need_to_check},
  16. 4: {'text': 'Вывести список непроверенных слов (answer_from_wiktionary = null)',
  17. 'function': print_list_of_words, 'params': 'null'},
  18. 5: {'text': 'Вывести список непроверенных слов c ошибкой 404 (answer_from_wiktionary = 404)',
  19. 'function': print_list_of_words, 'params': '404'},
  20. 6: {'text': 'Проверить подозрительные слова на сайтах', 'function': check_words_on_sites}
  21. }
  22. while True:
  23. print('')
  24. for key, value in menu.items():
  25. print('{} - {}'.format(key, value['text']))
  26. command = int(input('Введите номер команды (любой другой номер завершит программу): '))
  27. if command not in menu:
  28. break
  29. if 'params' not in menu[command]:
  30. menu[command]['function']()
  31. else:
  32. menu[command]['function'](menu[command]['params'])
  33. def clear_all_temporary_files():
  34. def delete_file(filename):
  35. if Path(dictionary_json_filename).is_file():
  36. os.remove(dictionary_json_filename)
  37. print('Файл {} удален'.format(dictionary_json_filename))
  38. else:
  39. print('Файл {} не существует'.format(dictionary_json_filename))
  40. start = time.time()
  41. delete_file(dictionary_json_filename)
  42. print('Временных файлов больше нет')
  43. end = time.time()
  44. print_time(start, end)
  45. def generated_json():
  46. start = time.time()
  47. if not is_exist_dictionary():
  48. return
  49. file = Path(dictionary_filename)
  50. with open(file, encoding='utf8') as f:
  51. lines = f.read().splitlines()
  52. dictionary = dict()
  53. for line in lines:
  54. split_line = line.split(' ', 1)
  55. word = split_line[0]
  56. definition = split_line[1]
  57. is_noun_by_dictionary = False
  58. if re.match(r'(ж|м|ср|мн)\.(.*)$', definition) or re.match(r'(1\.|I) (ж|м|ср|мн)\.(.*)$', definition):
  59. is_noun_by_dictionary = True
  60. is_possible_not_noun = False
  61. if (
  62. word.endswith('ая') or
  63. word.endswith('ее') or
  64. word.endswith('ие') or
  65. word.endswith('ий') or
  66. word.endswith('ое') or
  67. word.endswith('ой') or
  68. word.endswith('ые') or
  69. word.endswith('ый') or
  70. word.endswith('ье') or
  71. word.endswith('ьи') or
  72. word.endswith('ья') or
  73. word.endswith('яя')
  74. ):
  75. is_possible_not_noun = True
  76. entry = dict()
  77. entry['definition'] = definition
  78. entry['is_noun_by_dictionary'] = is_noun_by_dictionary
  79. entry['is_possible_not_noun'] = is_possible_not_noun
  80. entry['answer_from_wiktionary'] = 'null'
  81. dictionary[word] = entry
  82. save_json(dictionary)
  83. end = time.time()
  84. print_time(start, end)
  85. def how_many_articles_need_to_check():
  86. start = time.time()
  87. if not is_exist_json():
  88. return
  89. dictionary = read_json()
  90. count_all = 0
  91. count_nouns_by_dictionary = 0
  92. count_check = 0
  93. for word, entry in dictionary.items():
  94. count_all += 1
  95. if entry['is_noun_by_dictionary']:
  96. count_nouns_by_dictionary += 1
  97. if (
  98. entry['is_noun_by_dictionary'] and
  99. entry['is_possible_not_noun'] and
  100. entry['answer_from_wiktionary'] == 'null'
  101. ):
  102. count_check += 1
  103. print('Все слова: {}'.format(count_all))
  104. print('Количество существительных по Ефремовой: {}'.format(count_nouns_by_dictionary))
  105. print('Нужно проверить на сайтах: {}'.format(count_check))
  106. end = time.time()
  107. print_time(start, end)
  108. def print_list_of_words(answer_from_wiktionary):
  109. start = time.time()
  110. if not is_exist_json():
  111. return
  112. dictionary = read_json()
  113. count = 0
  114. for word, entry in dictionary.items():
  115. if entry['is_noun_by_dictionary'] and entry['is_possible_not_noun']:
  116. is_print = False
  117. if answer_from_wiktionary == 'null' and entry['answer_from_wiktionary'] == 'null':
  118. is_print = True
  119. if answer_from_wiktionary == '404' and entry['answer_from_wiktionary'] == 404:
  120. is_print = True
  121. if is_print:
  122. print(word)
  123. print('answer_from_wiktionary = {}'.format(entry['answer_from_wiktionary']))
  124. print('-------------------------')
  125. count += 1
  126. print('Слов: {}'.format(count))
  127. end = time.time()
  128. print_time(start, end)
  129. def check_words_on_sites():
  130. start = time.time()
  131. if not is_exist_json():
  132. return
  133. dictionary = read_json()
  134. i = 0
  135. for word, entry in dictionary.items():
  136. if (
  137. entry['is_noun_by_dictionary'] and
  138. entry['is_possible_not_noun'] and
  139. entry['answer_from_wiktionary'] == 'null'
  140. ):
  141. try:
  142. response = requests.get('https://ru.wiktionary.org/wiki/' + word)
  143. print('{} status_code = {}'.format(word, response.status_code))
  144. if response.status_code == 200:
  145. html = response.text
  146. is_noun_by_wiktionary = False
  147. is_not_noun_by_wiktionary = False
  148. if (
  149. 'title="существительное">Существительное</a>' in html or
  150. 'Существительное.' in html or
  151. 'title="выступает в роли существительного">субстантивир.</span>' in html or
  152. ('Существительное' in html and 'Прилагательное' not in html) or
  153. 'Существительное, одушевлённое, тип склонения по ' in html
  154. ):
  155. is_noun_by_wiktionary = True
  156. if (
  157. 'title="прилагательное">Прилагательное</a>' in html or
  158. 'title="причастие">Причастие</a>' in html or
  159. 'title="причастие">причастие</a>' in html or
  160. 'title="наречие">Наречие</a>' in html or
  161. 'title="деепричастие">деепричастие</a>' in html or
  162. ('Существительное' not in html and 'Прилагательное' in html) or
  163. ('Существительное' not in html and 'прилагательного' in html) or
  164. ('Существительное' not in html and 'Местоименное прилагательное' in html) or
  165. ('Существительное' not in html and 'Притяжательное местоимение' in html) or
  166. ('Существительное' not in html and 'Притяжательное прилагательное' in html) or
  167. ('Существительное' not in html and 'Числительное' in html) or
  168. ('Существительное' not in html and 'Порядковое числительное' in html) or
  169. ('Существительное' not in html and 'Местоимение' in html) or
  170. ('Существительное' not in html and 'Указательное местоимение' in html)
  171. ):
  172. is_not_noun_by_wiktionary = True
  173. if is_noun_by_wiktionary:
  174. dictionary[word]['answer_from_wiktionary'] = 'noun'
  175. print('answer_from_wiktionary = noun')
  176. if is_not_noun_by_wiktionary:
  177. dictionary[word]['answer_from_wiktionary'] = 'not_noun'
  178. print('answer_from_wiktionary = not_noun')
  179. if not is_noun_by_wiktionary and not is_not_noun_by_wiktionary:
  180. print('Need more checks')
  181. else:
  182. dictionary[word]['answer_from_wiktionary'] = response.status_code
  183. print('url = {}'.format(response.url))
  184. print('-------------------------')
  185. i += 1
  186. if i % 100 == 0:
  187. save_json(dictionary)
  188. except ConnectionError:
  189. print("Error: ConnectionError")
  190. time.sleep(1)
  191. i = 0
  192. for word, entry in dictionary.items():
  193. if (
  194. entry['is_noun_by_dictionary'] and
  195. entry['is_possible_not_noun'] and
  196. entry['answer_from_wiktionary'] == 404
  197. ):
  198. try:
  199. response = requests.get('https://dic.academic.ru/searchall.php?SWord=' + word)
  200. print('{} status_code = {}'.format(word, response.status_code))
  201. if response.status_code == 200:
  202. html = response.text
  203. is_noun_by_wiktionary = False
  204. is_not_noun_by_wiktionary = False
  205. if re.search(
  206. re.escape(
  207. word) + r'</a><\/strong> — сущ\.(.*?)<\/p>\n<p class="src"><a href="\/\/dic\.academic\.ru\/contents.nsf\/dic_synonims\/">Словарь синонимов<\/a><\/p>',
  208. html, re.S):
  209. is_noun_by_wiktionary = True
  210. if is_noun_by_wiktionary:
  211. dictionary[word]['answer_from_wiktionary'] = 'noun'
  212. print('answer_from_wiktionary = noun')
  213. # if is_not_noun_by_wiktionary:
  214. # dictionary[word]['answer_from_wiktionary'] = 'not_noun'
  215. # print('answer_from_wiktionary = not_noun')
  216. if not is_noun_by_wiktionary:
  217. print('Need more checks')
  218. print('-------------------------')
  219. i += 1
  220. if i % 100 == 0:
  221. save_json(dictionary)
  222. except ConnectionError:
  223. print("Ошибка: ConnectionError")
  224. time.sleep(1)
  225. save_json(dictionary)
  226. print('Проверка подозрительных слов завершена')
  227. end = time.time()
  228. print_time(start, end)
  229. def print_time(start, end):
  230. print('Время выполнения функции: {}'.format(time.strftime('%H:%M:%S', time.gmtime(end - start))))
  231. def save_json(dictionary):
  232. file = Path(dictionary_json_filename)
  233. action = 'обновлен' if file.is_file() else 'создан'
  234. with open(dictionary_json_filename, 'w', encoding='utf8') as outfile:
  235. json.dump(dictionary, outfile, ensure_ascii=False, indent=4)
  236. print('Файл {} {}'.format(dictionary_json_filename, action))
  237. def read_json():
  238. file = Path(dictionary_json_filename)
  239. with open(file, encoding='utf8') as f:
  240. dictionary = json.loads(f.read())
  241. print('Файл ' + dictionary_json_filename + ' открыт')
  242. return dictionary
  243. def is_exist_json():
  244. file = Path(dictionary_json_filename)
  245. if not file.is_file():
  246. print('Файл {} не существует. Его нужно сгенерировать первоначально.'.format(dictionary_json_filename))
  247. return file.is_file()
  248. def is_exist_dictionary():
  249. file = Path(dictionary_filename)
  250. if not file.is_file():
  251. print('Файл {} не существует. Программа не может быть выполнена.'.format(dictionary_filename))
  252. return file.is_file()
  253. def test():
  254. # print(urllib.parse.quote_plus('безносая', safe=''))
  255. pass
  256. if __name__ == '__main__':
  257. main()