Spaces:
Sleeping
Sleeping
Download src/clean.py from duvr/sentiment_analysis: direct link, hf CLI and curl.
- Browser
- Download file 4.11 kB
-
https://huggingface.co/spaces/duvr/sentiment_analysis/resolve/main/src/clean.py
- Command line
-
hf download hf://spaces/duvr/sentiment_analysis/src/clean.py
-
curl -L -o clean.py https://huggingface.co/spaces/duvr/sentiment_analysis/resolve/main/src/clean.py
4.11 kB
| 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 | |