Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Juan vizuete #6

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 41 additions & 41 deletions lessons/01_preprocessing.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -427,15 +427,15 @@
"id": "7bf0d8c8-bd6c-47ef-b305-09ac61d07d4d",
"metadata": {},
"source": [
"### Remove Extra Whitespace Characters\n",
"### Eliminar Caracteres de Espaciado Extra\n",
"\n",
"Sometimes we might come across texts with extraneous whitespace, such as spaces, tabs, and newline characters, which is particularly common when the text is scrapped from web pages. Before we dive into the details, let's briefly introduce Regular Expressions (regex) and the `re` package. \n",
"A veces nos encontramos con textos que contienen espacios en blanco innecesarios, como espacios, tabulaciones y caracteres de nueva línea, lo cual es particularmente común cuando el texto proviene de páginas web. Antes de profundizar en los detalles, presentemos brevemente las Expresiones Regulares (regex) y el paquete `re`. \n",
"\n",
"Regular expressions are a powerful way of searching for specific string patterns in large corpora. They have an infamously steep learning curve, but they can be very efficient when we get a handle on them. Many NLP packages heavily rely on regex under the hood. Regex testers, such as [regex101](https://regex101.com), are useful tools in both understanding and creating regex expressions.\n",
"Las expresiones regulares son una forma poderosa de buscar patrones específicos de cadenas en grandes corpus de texto. Tienen una curva de aprendizaje notoriamente empinada, pero pueden ser muy eficientes cuando logramos dominarlas. Muchos paquetes de procesamiento de lenguaje natural (NLP) dependen en gran medida de las expresiones regulares. Los probadores de regex, como [regex101](https://regex101.com), son herramientas útiles tanto para entender como para crear expresiones regulares.\n",
"\n",
"Our goal in this workshop is not to provide a deep (or even shallow) dive into regex; instead, we want to expose you to them so that you are better prepared to do deep dives in the future!\n",
"Nuestro objetivo en este taller no es ofrecer una inmersión profunda (ni siquiera superficial) en regex; en su lugar, queremos exponerlos a ellas para que estén mejor preparados para hacer inmersiones más profundas en el futuro.\n",
"\n",
"The following example is a poem by William Wordsworth. Like many poems, the text may contain extra line breaks (i.e., newline characters, `\\n`) that we want to remove."
"El siguiente ejemplo es un poema de William Wordsworth. Como muchos poemas, el texto puede contener saltos de línea extra (es decir, caracteres de nueva línea, `\\n`) que queremos eliminar."
]
},
{
Expand All @@ -459,7 +459,7 @@
"id": "7a693dd9-9706-40b3-863f-f568020245f7",
"metadata": {},
"source": [
"As you can see, the poem is formatted as a continuous string of text with line breaks placed at the end of each line, making it difficult to read. "
"Como pueden ver, el poema está formateado como una cadena continua de texto con saltos de línea al final de cada línea, lo que lo hace difícil de leer."
]
},
{
Expand Down Expand Up @@ -488,7 +488,7 @@
"id": "47cce993-c315-4aaa-87fe-149de8607f65",
"metadata": {},
"source": [
"One handy function we can use to display the poem properly is `.splitlines()`. As the name suggests, it splits a long text sequence into a list of lines whenever there is a newline character. "
"Una función útil que podemos usar para mostrar el poema correctamente es `.splitlines()`. Como su nombre indica, divide una secuencia de texto larga en una lista de líneas cada vez que encuentra un carácter de nueva línea."
]
},
{
Expand Down Expand Up @@ -547,7 +547,7 @@
"id": "44d3825b-0857-44e1-bf6a-d8c7a9032704",
"metadata": {},
"source": [
"Let's return to our tweet data for an example."
"Volvamos a nuestros datos de tweets para un ejemplo.\n"
]
},
{
Expand Down Expand Up @@ -578,9 +578,9 @@
"id": "aef55865-36fd-4c06-a765-530cf3b53096",
"metadata": {},
"source": [
"In this case, we don't really want to split the tweet into a list of strings. We still expect a single string of text but would like to remove the line break completely from the string.\n",
"En este caso, realmente no queremos dividir el tweet en una lista de cadenas. Aún esperamos una sola cadena de texto, pero nos gustaría eliminar el salto de línea completamente de la cadena.\n",
"\n",
"The string method `.strip()` effectively does the job of stripping away spaces at both ends of the text. However, it won't work in our example as the newline character is in the middle of the string."
"El método de cadenas `.strip()` hace eficazmente el trabajo de eliminar los espacios al principio y al final del texto. Sin embargo, no funcionará en nuestro ejemplo, ya que el carácter de nueva línea está en el medio de la cadena."
]
},
{
Expand Down Expand Up @@ -610,7 +610,7 @@
"id": "b99b80b4-804f-460f-a2d5-adbd654902b3",
"metadata": {},
"source": [
"This is where regex could be really helpful."
"Aquí es donde las expresiones regulares (regex) podrían ser realmente útiles."
]
},
{
Expand All @@ -628,13 +628,13 @@
"id": "d5f08d20-ba81-4e48-9e2a-5728148005b3",
"metadata": {},
"source": [
"Now, with regex, we are essentially calling it to match a pattern that we have identified in the text data, and we want to do some operations to the matched part—extract it, replace it with something else, or remove it completely. Therefore, the way regex works could be unpacked into the following steps:\n",
"Ahora, con las expresiones regulares (regex), esencialmente la estamos llamando para que coincida con un patrón que hemos identificado en los datos de texto, y queremos realizar algunas operaciones sobre la parte coincidente: extraerla, reemplazarla por algo más o eliminarla por completo. Por lo tanto, el funcionamiento de regex podría desglosarse en los siguientes pasos:\n",
"\n",
"- Identify and write the pattern in regex (`r'PATTERN'`)\n",
"- Write the replacement for the pattern (`'REPLACEMENT'`)\n",
"- Call the specific regex function (e.g., `re.sub()`)\n",
"- Identificar y escribir el patrón en regex (`r'PATTERN'`)\n",
"- Escribir el reemplazo para el patrón (`'REPLACEMENT'`)\n",
"- Llamar a la función específica de regex (por ejemplo, `re.sub()`)\n",
"\n",
"In our example, the pattern we are looking for is `\\s`, which is the regex short name for any whitespace character (`\\n` and `\\t` included). We also add a quantifier `+` to the end: `\\s+`. It means we'd like to capture one or more occurences of the whitespace character."
"En nuestro ejemplo, el patrón que estamos buscando es `\\s`, que es el nombre corto de regex para cualquier carácter de espacio en blanco (incluidos `\\n` y `\\t`). También agregamos un cuantificador `+` al final: `\\s+`. Esto significa que nos gustaría capturar una o más ocurrencias del carácter de espacio en blanco."
]
},
{
Expand All @@ -653,7 +653,7 @@
"id": "cc075c2e-1a1d-4393-a3ea-8ad7c118364b",
"metadata": {},
"source": [
"The replacement for one or more whitespace characters is exactly one single whitespace, which is the canonical word boundary in English. Any additional whitespace will be reduced to a single whitespace. "
"El reemplazo para uno o más caracteres de espacio en blanco es exactamente un solo espacio, que es el límite de palabra canónico en inglés. Cualquier espacio adicional se reducirá a un solo espacio."
]
},
{
Expand All @@ -672,7 +672,7 @@
"id": "bc12e3d1-728a-429b-9c83-4dcc88590bc4",
"metadata": {},
"source": [
"Lastly, let's put everything together using the function [`re.sub()`](https://docs.python.org/3.11/library/re.html#re.sub), which means we want to substitute a pattern with a replacement. The function takes in three arguments—the pattern, the replacement, and the string to which we want to apply the function."
"Finalmente, pongamos todo junto usando la función [`re.sub()`](https://docs.python.org/3.11/library/re.html#re.sub), lo que significa que queremos sustituir un patrón por un reemplazo. La función recibe tres argumentos: el patrón, el reemplazo y la cadena a la que queremos aplicar la función."
]
},
{
Expand Down Expand Up @@ -702,19 +702,19 @@
"id": "a895fbe3-a034-4124-94af-72a528913c51",
"metadata": {},
"source": [
"Ta-da! The newline character is no longer there."
"Ta-da! El carácter de nueva línea ya no está allí."
]
},
{
"cell_type": "markdown",
"id": "7087dc0c-5fef-4f1c-8662-7cbc8a978f34",
"metadata": {},
"source": [
"### Remove Punctuation Marks\n",
"### Eliminar los Signos de Puntuación\n",
"\n",
"Sometimes we are only interested in analyzing **alphanumeric characters** (i.e., the letters and numbers), in which case we might want to remove punctuation marks. \n",
"A veces solo estamos interesados en analizar **caracteres alfanuméricos** (es decir, las letras y los números), en cuyo caso podríamos querer eliminar los signos de puntuación.\n",
"\n",
"The `string` module contains a list of predefined punctuation marks. Let's print them out."
"El módulo `string` contiene una lista de signos de puntuación predefinidos. Vamos a imprimirlos."
]
},
{
Expand Down Expand Up @@ -742,7 +742,7 @@
"id": "91119c9e-431c-42cb-afea-f7e607698929",
"metadata": {},
"source": [
"In practice, to remove these punctuation characters, we can simply iterate over the text and remove characters found in the list, such as shown below in the `remove_punct` function."
"En la práctica, para eliminar estos caracteres de puntuación, podemos simplemente iterar sobre el texto y eliminar los caracteres que se encuentren en la lista, como se muestra a continuación en la función `remove_punct`.\n"
]
},
{
Expand Down Expand Up @@ -772,7 +772,7 @@
"id": "d4fc768b-c2dd-4386-8212-483c4485e4be",
"metadata": {},
"source": [
"Let's apply the function to the example below. "
"Aplicamos la función al siguiente ejemplo.\n"
]
},
{
Expand Down Expand Up @@ -815,7 +815,7 @@
"id": "853a4b83-f503-4405-aedd-66bbc088e3e7",
"metadata": {},
"source": [
"Let's give it a try with another tweet. What have you noticed?"
"Intentémoslo con otro tweet. ¿Qué has notado?\n"
]
},
{
Expand Down Expand Up @@ -857,7 +857,7 @@
"id": "1af02ce5-b674-4cb4-8e08-7d7416963f9c",
"metadata": {},
"source": [
"What about the following example?"
"¿Qué pasa con el siguiente ejemplo?\n"
]
},
{
Expand Down Expand Up @@ -890,24 +890,24 @@
"id": "62574c66-db3f-4500-9c3b-cea2f3eb2a30",
"metadata": {},
"source": [
"⚠️ **Warning:** In many cases, we want to remove punctuation marks **after** tokenization, which we will discuss in a minute. This tells us that the **order** of preprocessing is a matter of importance!"
"⚠️ **Advertencia:** En muchos casos, queremos eliminar los signos de puntuación **después** de la tokenización, lo cual discutiremos en un momento. ¡Esto nos dice que el **orden** del preprocesamiento es importante!\n"
]
},
{
"cell_type": "markdown",
"id": "58c6b85e-58e7-4f56-9b4a-b60c85b394ba",
"metadata": {},
"source": [
"## 🥊 Challenge 1: Preprocessing with Multiple Steps\n",
"## 🥊 Desafío 1: Preprocesamiento con Múltiples Pasos\n",
"\n",
"So far we've learned a few preprocessing operations, let's put them together in a function! This function would be a handy one to refer to if you happen to work with some messy English text data, and you want to preprocess it with a single function. \n",
"Hasta ahora hemos aprendido algunas operaciones de preprocesamiento, ¡vamos a combinarlas en una función! Esta función sería útil para referirse a ella si alguna vez trabajas con datos de texto en inglés desordenados y deseas preprocesarlos con una sola función.\n",
"\n",
"The example text data for challenge 1 is shown below. Write a function to:\n",
"- Lowercase the text\n",
"- Remove punctuation marks\n",
"- Remove extra whitespace characters\n",
"Los datos de texto de ejemplo para el desafío 1 se muestran a continuación. Escribe una función que:\n",
"- Ponga el texto en minúsculas\n",
"- Elimine los signos de puntuación\n",
"- Elimine los caracteres de espacio en blanco extra\n",
"\n",
"Feel free to recycle the codes we've used above!"
"¡Siéntete libre de reutilizar los códigos que hemos usado anteriormente!\n"
]
},
{
Expand Down Expand Up @@ -986,25 +986,25 @@
"id": "67c159cb-8eaa-4c30-b8ff-38a712d2bb0f",
"metadata": {},
"source": [
"## Task-specific Processes\n",
"## Procesos Específicos para Tareas\n",
"\n",
"Now that we understand common preprocessing operations, there are still a few additional operations to consider. Our text data might require further normalization depending on the language, source, and content of the data.\n",
"Ahora que entendemos las operaciones comunes de preprocesamiento, aún hay algunas operaciones adicionales a considerar. Nuestros datos de texto pueden requerir una mayor normalización dependiendo del idioma, la fuente y el contenido de los datos.\n",
"\n",
"For example, if we are working with financial documents, we might want to standardize monetary symbols by converting them to digits. It our tweets data, there are numerous hashtags and URLs. These can be replaced with placeholders to simplify the subsequent analysis."
"Por ejemplo, si estamos trabajando con documentos financieros, podríamos querer estandarizar los símbolos monetarios convirtiéndolos en dígitos. En nuestros datos de tweets, hay numerosos hashtags y URLs. Estos pueden ser reemplazados por marcadores de posición para simplificar el análisis posterior.\n"
]
},
{
"cell_type": "markdown",
"id": "c2936cea-74e9-40c2-bfbe-6ba8129330de",
"metadata": {},
"source": [
"### 🎬 **Demo**: Remove Hashtags and URLs \n",
"### 🎬 **Demostración**: Eliminar Hashtags y URLs\n",
"\n",
"Although URLs, hashtags, and numbers are informative in their own right, oftentimes we don't necessarily care about the exact meaning of each of them. \n",
"Aunque las URLs, los hashtags y los números son informativos por derecho propio, a menudo no nos importa necesariamente el significado exacto de cada uno de ellos.\n",
"\n",
"While we could remove them completely, it's often informative to know that there **exists** a URL or a hashtag. In practice, we replace individual URLs and hashtags with a \"symbol\" that preserves the fact these structures exist in the text. It's standard to just use the strings \"URL\" and \"HASHTAG.\"\n",
"Si bien podríamos eliminarlos por completo, a menudo es informativo saber que **existe** una URL o un hashtag. En la práctica, reemplazamos las URLs y los hashtags individuales por un \"símbolo\" que conserva el hecho de que estas estructuras existen en el texto. Es común usar simplemente las cadenas \"URL\" y \"HASHTAG\".\n",
"\n",
"Since these types of text often follow a regular structure, they're an apt case for using regular expressions. Let's apply these patterns to the tweets data."
"Dado que estos tipos de texto suelen seguir una estructura regular, son un buen caso para usar expresiones regulares. Apliquemos estos patrones a los datos de tweets.\n"
]
},
{
Expand Down
Loading