Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Пользователь с клавиатуры вводит путь к существующей
- директории и слово для поиска. После чего запускаются
- два потока. Первый должен найти файлы, содержащие
- искомое слово и слить их содержимое в один файл. Второй поток ожидает завершения работы первого потока.
- После чего проводит вырезание всех запрещенных слов
- (список этих слов нужно считать из файла с запрещенными словами) из полученного файла. На экран необходимо
- отобразить статистику выполненных операций.
- """
- import threading
- import os
- def find_words(directory, word, result_file):
- with open(result_file, "w", encoding="utf-8") as output:
- for root, subdir, files in os.walk(directory):
- for file in files:
- file_path = os.path.join(root, file)
- try:
- with open(file_path, "r", encoding="utf-8") as current_file:
- content = current_file.read()
- if word in content:
- output.write(f"~~~ {file_path} ~~~\n")
- output.write(f"{content}\n")
- except Exception as exc:
- print(f"Ошибка при чтении файла {file_path}: {exc}")
- def remove_words(input_file, banned_words_file, result_file):
- with open(input_file, "r", encoding="utf-8") as current_file:
- content = current_file.read()
- with open(banned_words_file, "r", encoding="utf-8") as banned:
- banned_words = set(banned.read().splitlines())
- for banned_word in banned_words:
- content = content.replace(banned_word, "[BANNED]")
- with open(result_file, "w", encoding="utf-8") as result:
- result.write(content)
- directory = input("Введите путь к существующей директории: ").replace("\"", "")
- word = input("Введите слово для поиска: ")
- result_file = input("Введите путь к итоговому файлу: ").replace("\"", "")
- banned_words = input("Введите путь к файлу c запрещёнными словами: ").replace("\"", "")
- search_thread = threading.Thread(target=find_words, args=[directory, word, result_file])
- cleanup_thread = threading.Thread(target=remove_words, args=[result_file, banned_words, "edited_file.txt"])
- if not os.path.exists(directory):
- print("Директория не существует!")
- else:
- search_thread.start()
- search_thread.join()
- with open(result_file, "r", encoding="utf-8") as check_file:
- content = check_file.read()
- if not content:
- print("Искомого слова в файлах нет!")
- else:
- if not os.path.exists(banned_words):
- print("Файла с запрещёнными словами не существует!")
- else:
- cleanup_thread.start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement