Advertisement
plarmi

threading4

Apr 22nd, 2024 (edited)
607
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.18 KB | None | 0 0
  1. """
  2. Пользователь с клавиатуры вводит путь к существующей
  3. директории и слово для поиска. После чего запускаются
  4. два потока. Первый должен найти файлы, содержащие
  5. искомое слово и слить их содержимое в один файл. Второй поток ожидает завершения работы первого потока.
  6. После чего проводит вырезание всех запрещенных слов
  7. (список этих слов нужно считать из файла с запрещенными словами) из полученного файла. На экран необходимо
  8. отобразить статистику выполненных операций.
  9. """
  10. import threading
  11. import os
  12.  
  13. def find_words(directory, word, result_file):
  14.     with open(result_file, "w", encoding="utf-8") as output:
  15.         for root, subdir, files in os.walk(directory):
  16.             for file in files:
  17.                 file_path = os.path.join(root, file)
  18.                 try:
  19.                     with open(file_path, "r", encoding="utf-8") as current_file:
  20.                         content = current_file.read()
  21.                         if word in content:
  22.                             output.write(f"~~~ {file_path} ~~~\n")
  23.                             output.write(f"{content}\n")
  24.                 except Exception as exc:
  25.                     print(f"Ошибка при чтении файла {file_path}: {exc}")
  26.  
  27. def remove_words(input_file, banned_words_file, result_file):
  28.     with open(input_file, "r", encoding="utf-8") as current_file:
  29.         content = current_file.read()
  30.  
  31.     with open(banned_words_file, "r", encoding="utf-8") as banned:
  32.         banned_words = set(banned.read().splitlines())
  33.  
  34.     for banned_word in banned_words:
  35.         content = content.replace(banned_word, "[BANNED]")
  36.  
  37.     with open(result_file, "w", encoding="utf-8") as result:
  38.         result.write(content)
  39.  
  40.  
  41. directory = input("Введите путь к существующей директории: ").replace("\"", "")
  42. word = input("Введите слово для поиска: ")
  43. result_file = input("Введите путь к итоговому файлу: ").replace("\"", "")
  44. banned_words = input("Введите путь к файлу c запрещёнными словами: ").replace("\"", "")
  45.  
  46. search_thread = threading.Thread(target=find_words, args=[directory, word, result_file])
  47. cleanup_thread = threading.Thread(target=remove_words, args=[result_file, banned_words, "edited_file.txt"])
  48.  
  49.  
  50. if not os.path.exists(directory):
  51.     print("Директория не существует!")
  52. else:
  53.     search_thread.start()
  54.  
  55. search_thread.join()
  56.  
  57. with open(result_file, "r", encoding="utf-8") as check_file:
  58.     content = check_file.read()
  59.  
  60. if not content:
  61.     print("Искомого слова в файлах нет!")
  62. else:
  63.     if not os.path.exists(banned_words):
  64.         print("Файла с запрещёнными словами не существует!")
  65.     else:
  66.         cleanup_thread.start()
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement