Skip to content

Commit 21ac2fa

Browse files
Codewords_Searcher.py
1 parent 2eb401b commit 21ac2fa

File tree

1 file changed

+62
-62
lines changed

1 file changed

+62
-62
lines changed

Codewords Searcher.py

+62-62
Original file line numberDiff line numberDiff line change
@@ -8,90 +8,90 @@
88
import logging
99
from colorama import Fore, Style, init
1010

11-
def buscar_texto_en_archivos(carpeta, palabras_buscar):
12-
archivos_encontrados = []
13-
tipos_archivo_buscar = ['.php', '.js', '.html', '.json', '.ini', '.css']
11+
def search_text_in_files(folder, search_words):
12+
found_files = []
13+
file_types_to_search = ['.php', '.js', '.html', '.json', '.ini', '.css']
1414

15-
# Escapar caracteres especiales en cada palabra buscada
16-
palabras_buscar_regex = [re.escape(palabra) for palabra in palabras_buscar]
15+
# Escape special characters in each search word
16+
search_words_regex = [re.escape(word) for word in search_words]
1717

18-
# Crear una expresión regular que buscará todas las palabras
19-
texto_buscar_regex = re.compile(r"|".join(palabras_buscar_regex), re.IGNORECASE)
18+
# Create a regular expression that will search for all the words
19+
search_text_regex = re.compile(r"|".join(search_words_regex), re.IGNORECASE)
2020

21-
# Configurar el sistema de logs con color
22-
init(autoreset=True) # Inicializar colorama
21+
# Configure logging system with colors
22+
init(autoreset=True) # Initialize colorama
2323
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
24-
logger = logging.getLogger('buscador_log')
24+
logger = logging.getLogger('search_log')
2525

26-
# Recorre todos los archivos en la carpeta y sus subcarpetas
27-
for ruta_actual, carpetas, archivos in os.walk(carpeta):
28-
# Excluye ciertas carpetas si es necesario
29-
# Por ejemplo, si deseas excluir la carpeta 'excluir_carpeta':
30-
# if 'excluir_carpeta' in carpetas:
31-
# carpetas.remove('excluir_carpeta')
26+
# Traverse all files in the folder and its subfolders
27+
for current_path, folders, files in os.walk(folder):
28+
# Exclude certain folders if necessary
29+
# For example, if you want to exclude the folder 'exclude_folder':
30+
# if 'exclude_folder' in folders:
31+
# folders.remove('exclude_folder')
3232

33-
for archivo in archivos:
34-
# Comprueba si el archivo tiene una extensión de archivo válida
35-
if any(archivo.endswith(extension) for extension in tipos_archivo_buscar):
36-
ruta_completa = os.path.join(ruta_actual, archivo)
33+
for file in files:
34+
# Check if the file has a valid file extension
35+
if any(file.endswith(extension) for extension in file_types_to_search):
36+
full_path = os.path.join(current_path, file)
3737

3838
try:
39-
# Lee el contenido del archivo
40-
with open(ruta_completa, 'r', encoding='utf-8') as archivo_contenido:
41-
contenido = archivo_contenido.read().lower() # Convierte el contenido a minúsculas
39+
# Read the content of the file
40+
with open(full_path, 'r', encoding='utf-8') as file_content:
41+
content = file_content.read().lower() # Convert content to lowercase
4242

43-
# Imprime las palabras que se están buscando en el archivo actual
44-
logger.info(f"{Fore.RED}Buscando palabras en el archivo: {ruta_completa} - Palabras: {', '.join(palabras_buscar)}")
43+
# Print the words being searched in the current file
44+
logger.info(f"{Fore.RED}Searching words in file: {full_path} - Word: {', '.join(search_words)}")
4545

46-
# Busca todas las palabras en el contenido utilizando la expresión regular
47-
resultados = texto_buscar_regex.finditer(contenido)
48-
for resultado in resultados:
49-
archivos_encontrados.append((ruta_completa, resultado.group()))
46+
# Search all words in the content using the regular expression
47+
results = search_text_regex.finditer(content)
48+
for result in results:
49+
found_files.append((full_path, result.group()))
5050

51-
# Imprime el resultado con la palabra encontrada en amarillo
52-
resultado_coloreado = re.sub(resultado.group(), f"{Fore.YELLOW}{resultado.group()}{Fore.WHITE}", resultado.group())
53-
logger.info(f"{Fore.WHITE}{Style.BRIGHT}Texto encontrado en el archivo: {ruta_completa} - Palabra encontrada: {resultado_coloreado}")
51+
# Print the result with the found word in yellow
52+
colored_result = re.sub(result.group(), f"{Fore.YELLOW}{result.group()}{Fore.WHITE}", result.group())
53+
logger.info(f"{Fore.WHITE}{Style.BRIGHT}Text found in file: {full_path} - Found word: {colored_result}")
5454
except Exception as e:
55-
logger.error(f"{Fore.RED}Error al abrir el archivo {ruta_completa}: {e}")
55+
logger.error(f"{Fore.RED}Error while opening the file {full_path}: {e}")
5656

57-
return archivos_encontrados
57+
return found_files
5858

59-
def obtener_palabras_buscadas():
60-
# Obtener las palabras a buscar utilizando un cuadro de diálogo
61-
palabras_buscadas = simpledialog.askstring("Codewords v1.2 by @FreddyDeveloper", "Ingrese las palabras que desea buscar en el código separadas por comas:")
59+
def get_search_words():
60+
# Get the words to search using a dialog box
61+
search_words = simpledialog.askstring("Codewords v1.2 by @FreddyDeveloper", "Enter the words you want to search in the code separated by commas:")
6262

63-
if not palabras_buscadas:
64-
messagebox.showwarning("Advertencia", "No se ingresaron palabras de búsqueda.")
63+
if not search_words:
64+
messagebox.showwarning("Warning", "No search words were entered.")
6565
return None
6666

67-
# Convertir las palabras ingresadas en una lista
68-
palabras_buscadas = [palabra.strip() for palabra in palabras_buscadas.split(",")]
69-
return palabras_buscadas
67+
# Convert the entered words into a list
68+
search_words = [word.strip() for word in search_words.split(",")]
69+
return search_words
7070

71-
# Crear una ventana de Tkinter para que el usuario seleccione la carpeta de búsqueda
71+
# Create a Tkinter window for the user to select the search folder
7272
app = tk.Tk()
73-
app.withdraw() # Oculta la ventana principal
73+
app.withdraw() # Hide the main window
7474

75-
# Obtener las palabras a buscar
76-
palabras_buscadas = obtener_palabras_buscadas()
75+
# Get the words to search
76+
search_words = get_search_words()
7777

78-
if palabras_buscadas is None:
79-
messagebox.showwarning("Advertencia", "No se ingresaron palabras de búsqueda. Saliendo...")
78+
if search_words is None:
79+
messagebox.showwarning("Warning", "Exiting...")
8080
else:
81-
# Seleccionar la carpeta de búsqueda
82-
carpeta_seleccionada = filedialog.askdirectory(title="Selecciona una carpeta para iniciar la búsqueda:")
81+
# Select the search folder
82+
selected_folder = filedialog.askdirectory(title="Select a folder to start the search:")
8383

84-
if not carpeta_seleccionada:
85-
messagebox.showwarning("Advertencia", "No se ha seleccionado ninguna carpeta. Saliendo...")
84+
if not selected_folder:
85+
messagebox.showwarning("Warning", "No folder has been selected. Exiting...")
8686
else:
87-
# Llamar a la función para buscar las palabras en los archivos
88-
archivos_encontrados = buscar_texto_en_archivos(carpeta_seleccionada, palabras_buscadas)
89-
90-
# Imprime los resultados en colores y formato personalizados
91-
if archivos_encontrados:
92-
print(f"{Fore.GREEN}{Style.BRIGHT}Texto encontrado en los siguientes archivos:")
93-
for ruta_completa, palabra_encontrada in archivos_encontrados:
94-
print(f"{Fore.GREEN}{Style.BRIGHT}{ruta_completa}")
95-
print(f"{Fore.YELLOW}{Style.BRIGHT}Palabra encontrada: {palabra_encontrada}{Fore.WHITE}")
87+
# Call the function to search for words in the files
88+
found_files = search_text_in_files(selected_folder, search_words)
89+
90+
# Print the results with custom colors and formatting
91+
if found_files:
92+
print(f"{Fore.GREEN}{Style.BRIGHT}Text found in the following files:")
93+
for full_path, found_word in found_files:
94+
print(f"{Fore.GREEN}{Style.BRIGHT}{full_path}")
95+
print(f"{Fore.YELLOW}{Style.BRIGHT}Found word: {found_word}{Fore.WHITE}")
9696
else:
97-
print(f"{Fore.RED}{Style.BRIGHT}Texto no encontrado en ningún archivo.")
97+
print(f"{Fore.RED}{Style.BRIGHT}Text not found in any file.")

0 commit comments

Comments
 (0)