|
| 1 | +# Challenge Description and Solution |
| 2 | + |
| 3 | +## English Version |
| 4 | + |
| 5 | +### Challenge Description |
| 6 | +Create a function that counts the frequency of each word in a given text. Consider normalization of case and removal of punctuation. |
| 7 | + |
| 8 | +### Code Explanation |
| 9 | +The `wordFrequency` function converts the text to lowercase, removes punctuation using a regex, and then counts the frequency of each word using an object. |
| 10 | + |
| 11 | +### Relevant Code Snippet |
| 12 | + |
| 13 | +```javascript |
| 14 | +function wordFrequency(text) { |
| 15 | + const punctuationRegex = /[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/g; |
| 16 | + text = text.toLowerCase().replace(punctuationRegex, ''); |
| 17 | + const words = text.split(/\s+/); |
| 18 | + const freq = {}; |
| 19 | + for (const word of words) { |
| 20 | + if (word.length === 0) continue; |
| 21 | + freq[word] = (freq[word] || 0) + 1; |
| 22 | + } |
| 23 | + return freq; |
| 24 | +} |
| 25 | +``` |
| 26 | + |
| 27 | +### Example Usage |
| 28 | + |
| 29 | +```javascript |
| 30 | +const sampleText = "Hello world! Hello everyone. Welcome to the world of Python."; |
| 31 | +const frequencies = wordFrequency(sampleText); |
| 32 | +for (const [word, count] of Object.entries(frequencies)) { |
| 33 | + console.log(`'${word}': ${count}`); |
| 34 | +} |
| 35 | +``` |
| 36 | + |
| 37 | +--- |
| 38 | + |
| 39 | +## Versión en Español |
| 40 | + |
| 41 | +### Descripción del Reto |
| 42 | +Crea una función que cuente la frecuencia de cada palabra en un texto dado. Considera la normalización de mayúsculas y minúsculas y la eliminación de signos de puntuación. |
| 43 | + |
| 44 | +### Explicación del Código |
| 45 | +La función `wordFrequency` convierte el texto a minúsculas, elimina signos de puntuación usando una expresión regular, y luego cuenta la frecuencia de cada palabra utilizando un objeto. |
| 46 | + |
| 47 | +### Fragmento de Código Relevante |
| 48 | + |
| 49 | +```javascript |
| 50 | +function wordFrequency(text) { |
| 51 | + const punctuationRegex = /[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/g; |
| 52 | + text = text.toLowerCase().replace(punctuationRegex, ''); |
| 53 | + const words = text.split(/\s+/); |
| 54 | + const freq = {}; |
| 55 | + for (const word of words) { |
| 56 | + if (word.length === 0) continue; |
| 57 | + freq[word] = (freq[word] || 0) + 1; |
| 58 | + } |
| 59 | + return freq; |
| 60 | +} |
| 61 | +``` |
| 62 | + |
| 63 | +### Ejemplo de Uso |
| 64 | + |
| 65 | +```javascript |
| 66 | +const sampleText = "Hello world! Hello everyone. Welcome to the world of Python."; |
| 67 | +const frequencies = wordFrequency(sampleText); |
| 68 | +for (const [word, count] of Object.entries(frequencies)) { |
| 69 | + console.log(`'${word}': ${count}`); |
| 70 | +} |
0 commit comments