Spaces:
Sleeping
Sleeping
File size: 4,109 Bytes
fe45c80 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | import re
import os
from symspellpy import SymSpell
import unicodedata
from bs4 import BeautifulSoup
def replace_nbsp(texto: str):
"""Reemplazar el símbolo por un espacio regular"""
return re.sub(r"[\xa0]", " ", str(texto))
def replace_quotes(text: str):
"""Reemplazar comillas dobles por comillas simples"""
texto = re.sub(r'"', "'", text)
texto = re.sub(r"[“”]", "'", texto) # Para comillas curvas
texto = re.sub(r""", "'", texto) # Para la entidad HTML
return texto
def remove_html(text: str):
# clean_text = re.sub(r'<[^>]+>', '', text)
soup = BeautifulSoup(text, "html.parser")
clean_text = soup.get_text() # Extraer texto de código html
return clean_text
def normalize_text(text: str):
"""Convertir texto en negritas, cursivas a su forma normal y
Unír unir acentos
"""
# Eliminar negritas, cursivas, separar acentos, etc.
text = unicodedata.normalize("NFKD", str(text))
# Unir acentos para evitar problemas
text = unicodedata.normalize("NFC", text)
return text
def replace_url(text: str, value="url"):
"""Reemplazar una url por otro valor"""
return re.sub(r"https?://\S+|www\.\S+", value, text)
def remove_punctuation(text: str):
return re.sub(r'[!"#&\'*+,-./<=>?@:;_%&¿<>()[\\]^`{|}~]', "", text)
def filter_text(text: str):
pattern = re.compile(r"([a-zA-ZáéíóúüÁÉÍÓÚÜñÑ0-9]+)", re.UNICODE)
return " ".join(pattern.findall(text))
def replace_whitespaces(text: str):
"""Reemplazar espacios consecutivos, al inicio, final o intermedios por uno solo"""
return re.sub(r"\s+", " ", text).strip()
SYMSPELL_DICTIONARIES_PATHS = {
"en": os.path.join(os.getcwd(), "src", "en-80k.txt"),
"es": os.path.join(os.getcwd(), "src", "es-100l.txt"),
}
spell_es = SymSpell(
max_dictionary_edit_distance=2, # Distancia de búsqueda
prefix_length=7, # Prefijos de palabras
)
load = spell_es.load_dictionary(
SYMSPELL_DICTIONARIES_PATHS["es"],
term_index=0, # posicion donde se encuentran los terminos
count_index=1, # posicion donde se encuentran las frecuencias
encoding="utf-8",
)
if not load:
print("[sympellpy]: No ha sido posible cargar el diccionario en español")
spell_en = SymSpell(
max_dictionary_edit_distance=2, # Distancia de búsqueda
prefix_length=7, # Prefijos de palabras
)
load = spell_en.load_dictionary(
SYMSPELL_DICTIONARIES_PATHS["en"],
term_index=0, # posicion donde se encuentran los terminos
count_index=1, # posicion donde se encuentran las frecuencias
encoding="utf-8",
)
if not load:
print("[sympellpy]: No ha sido posible cargar el diccionario en inglés")
spellers = {"es": spell_es, "en": spell_en}
def spell(texto, lang="es"):
if lang not in SYMSPELL_DICTIONARIES_PATHS.keys():
print(f"Idioma no soportado: {lang}")
return None
spell = spellers[lang]
sugerencias = spell.lookup_compound(
texto,
max_edit_distance=2,
ignore_non_words=True, # ignorar caracteres como números
)
return sugerencias[0].term
def clean_text(text: str, lang="es"):
"""Mantienen letras en español, acentos y algunos signos de puntuación.
Elimina emojis
"""
# Convertir a minúsculas
text = text.lower()
# Reemplazar por espacios regulares
text = replace_nbsp(text)
## Convertir comillas dobles a comilla simple
text = replace_quotes(text)
# Eliminar etiquetas html
text = remove_html(text)
# Normalizar texto en negritas, italicas, etc
text = normalize_text(text)
# Reemplazar urls
text = replace_url(text, " ")
# Eliminar signos de puntuación
text = remove_punctuation(text)
# Filtrar palabras con letras del español (elimina, emojis, símbolos espaciales, etc)
text = filter_text(text)
# Eliminar espacios, tabulaciones, etc consecutivos
text = replace_whitespaces(text)
# Corrección ortográfica
text = spell(text, lang)
# Remover stopwords
# text = get_no_stopwords(text, lang)
return text
|