Hola compañeros de la comunidad de Hive, como lo dice el título, hoy les enseñaré a como crear una nube de palabras utilizando Python3 con el módulo wordcloud de una forma sencilla con pocas líneas de código. Esto con el fin de que puedan analizar cuales son las palabras que más frecuencia aparecen en sus post o simplemente para agregarle un cierto atractivo o adorno visual.
> Hello colleagues of the Hive community, as the title says, today I will teach you how to create a word cloud using Python3 with the wordcloud module in a simple way with few lines of code. This so that they can analyze what are the words that most frequently appear in their posts or simply add a particular attraction or visual ornament.
Una nube de palabras es una representación visual de las palabras utilizadas en un escrito, en donde estas se muestran con distintos tamaños según la frecuencia con la que aparecen. Por ejemplo, la siguiente imagen fue creada con el texto de las entradas de [hive.io](https://hive.io/)
> A word cloud is a visual representation of the words used in a piece of writing, where they are shown in different sizes depending on how often they appear. For example, the following image was created with the text of the [hive.io](https://hive.io/) entries.


En esta primer parte del tutorial van a aprender a:
1. Como generar una nube de palabras sencilla.
2. Ajustar el color de fondo, el color de las palabras, el tamaño de la imagen, entre otras opciones.
3. Guardar su nube de palabras como imagen.
> In this first part of the tutorial, they will learn to:
>1. How to generate a simple word cloud.
>2. Adjust the background color, word color, image size, among other options.
>3. Save your word cloud as an image.

## Prerrequisitos | Setup
Primero asegúrense de tener Python3, después deben tener instalada en su equipo de cómputo la siguiente biblioteca:
- ```wordcloud```
>First, make sure you have Python3, then you must have the following library installed on your computer:
• wordcloud
Si no la tienen, pueden usar el siguiente comando:
>If they don't have them, you can use the following command:
```shellscript
pip3 install wordcloud
```
Si tienen anaconda, pueden usar el siguiente comando:
>If they have anaconda, you can use the following command:
```shellscript
conda install -c conda-forge wordcloud
```

## Lo básico | Basics
Primero debemos colocar los módulos que vamos a utilizar.
> First, we must place the modules that we are going to use.
```python
from wordcloud import WordCloud
```
- Wordcloud, nos ayudará a generar la nube de palabras.
> - Wordcloud will help us generate the word cloud.
En la siguiente parte se tiene el código que va a leer el texto de nuestro post o cualquier otro escrito del cual se tomará como referencia para crear la nube de palabras. Por ejemplo, el siguiente texto lo tomé de las entradas de [hive.io](https://hive.io/).
> In the next part, we have the code that will read the text of our post or any other writing that will be taken as a reference to create the word cloud. For example, the following text I received from the entries of [hive.io](https://hive.io/).
```language
Fast.
Scalable.
Powerful.
The Blockchain for Web 3.0
Developed for Web 3.0
Hive is an open-source blockchain, forged in years of development to bring Web 3.0 to the world. With a diverse community of stakeholders and without controlling bad actors, individuals can experience true ownership in a decentralised blockchain & cryptocurrency.
Why choose Hive?
Fast.
Transactions take less than 3 seconds
Scalable.
Future proof resource-bandwidth & storage system.
Powerful.
Battle-tested for 4 years by hundreds of apps, communities & projects around the world.
Hive Ecosystem
Hive has a thriving ecosystem of apps, communities & individuals, leveraging the Hive blockchain & decentralised structure.
Hive.Blog
Peakd
3Speak
Splinterlands
Esteem
STEMsocial
SteemPress
Actifit
DLease
Engrave
BROsino
BRO Poker
Choose your Wallet
Hive wallets are available for Windows, MacOS, Linux, iOS, Android & Web.
Vessel
Keychain
HiveWallet
Esteem
HiveSigner
Peakd
Hive.Blog
```
Este texto debemos guardarlo en un archivo .txt (puede ser también texto en .csv, pero será para otra ocasión). Con fines de ejemplo lo nombraré como ``` hive.txt ```. Para guardar todo el escrito en una variable usamos lo siguiente.
> This text must save in a .txt file (it may also be text in .csv, but it will be for another occasion). For example purposes, I will name it as ``` hive.txt ```. To save all the writing in a variable; we use the following.
```python
textwc = ""
with open('test.txt', encoding='utf-8') as f:
textwc = ''.join(f.readlines())
```
Es importante que agregar ```utf-8``` para que detecte palabras con acento.
> It is important that you add ``` utf-8``` so that it detects words with an accent.
Para inicializar las características de la nube de palabras en nuestra variable ```textwc``` se tiene que usar la función ```WordCloud()```.
> To initialize the characteristics of the word cloud in our variable ```textwc```, you must use the function ```WordCloud()```.
```python
wordcloud = WordCloud()
```
Esta función admite una amplia cantidad de parámetros, les enlistaré lo que usualmente utilizo.
- ```font_path``` → Aquí se específica la ruta de alguna fuente en particular que se quiera utilizar.
- ```width``` → Es el ancho del canvas.
- ```height``` → Es la altura del canvas.
- ```mask``` → Ayuda a crear una nube de palabras tomando el contorno de una imagen (esto se verá en el siguiente post).
- ```color_func``` → Sirve para crear nubes de palabras con un solo color.
- ```max_words``` → Es el número máximo de palabras que puede haber en nuestra nube.
- ```min_font_size``` → Es el tamaño mínimo de letra.
- ```stopwords``` → Sirve para evitar que aparezcan los pronombres personales, artículos determinados e indeterminados, así como palabras que realmente no aportan o no son significantes en el escrito. Esta función se presentará más adelante.
- ```background_color``` → Color de fondo, usualmente utilizo blanco y negro, pero se puede utilizar cualquier color que se encuentre [aquí](https://matplotlib.org/3.1.0/tutorials/colors/colors.html). Color por defecto: negro.
- ```max_font_size``` → Es el tamaño máximo de la letra.
- ```colormap``` → Se utiliza para colocar colores al azar dependiendo de la configuración que se eliga de [aquí](https://matplotlib.org/3.2.1/tutorials/colors/colormaps.html).
- ```contour_width``` → Es el ancho del contorno generado por mask.
- ```contour_color``` → Es el color del contorno generado por mask.
> This function supports a vast number of parameters. I will list what I usually use.
> - ```font_path``` → Here, the path of some particular font that you want to use is specified.
> - ```width``` → It is the width of the canvas.
> - ```height``` → It is the height of the canvas.
> - ```mask``` → Help create a word cloud by taking the outline of an image (this will be seen in the next post).
> - ```color_func``` → It is used to create word clouds with a single color.
> - ```max_words``` → It is the maximum number of words that can be in our cloud.
> - ```min_font_size``` → It is the minimum font size.
> - ```stopwords``` → It serves to prevent the appearance of personal pronouns, specific and indefinite articles, as well as words that do not really contribute or are not significant in writing. This feature will be introduced later.
> - ```background_color``` → Background color, I usually use black and white, but you can use any color found [here](https://matplotlib.org/3.1.0/tutorials/colors/colors.html). Default color: black.
> - ```max_font_size``` → It is the maximum font size.
> - ```colormap``` → It is used to place colors at random depending on the configuration chosen from [here](https://matplotlib.org/3.2.1/tutorials/colors/colormaps.html).
> - ```contour_width``` → It is the width of the contour generated by the mask.
> - ```contour_color``` → It is the color of the contour made by the mask.
Una vez que se inicializan las características de la nube de palabras con los atributos por defecto o los modificados, se tiene que utilizar la función ```generate()``` para poder generar la nube a partir del texto.
> Once the characteristics of the word cloud are initialized with the default or modified attributes, the ```generated()``` function must be used to create the cloud from the text.
```python
wordcloud.generate(textwc)
```
Por último, solo queda guardar la imagen con la función ```to_file()```.
> Finally, it only remains to save the image with the ```to_file()``` function.
```python
wordcloud.to_file('hive.png')
```

## Código básico completo | Complete basic code
```python
from wordcloud import WordCloud
textwc = ""
with open('hive.txt', encoding='utf-8') as f:
textwc = ''.join(f.readlines())
wordcloud = WordCloud()
wordcloud.generate(textwc)
wordcloud.to_file('hive.png')
```
### Resultado | Result


## Código modificado | Modified code
```python
from wordcloud import WordCloud
textwc = ""
with open('hive.txt', encoding='utf-8') as f:
textwc = ''.join(f.readlines())
wordcloud = WordCloud(font_path = "/usr/share/fonts/truetype/andika/Andika-R.ttf",
width = 4000,
height = 2000,
mask = None,
color_func = None,
max_words = 300,
min_font_size = 12,
stopwords = None,
background_color = "gray",
max_font_size = 300,
colormap = "gist_heat",
contour_width = 0,
contour_color = "white")
wordcloud.generate(textwc)
wordcloud.to_file('hive_mod.png')
```
### Resultado | Result


## Eliminar palabras vacías | Delete stopwords
Para eliminar las palabras vacías, que son aquellas que carecen de significado propio se puede utilizar la función de ```STOPWORDS``` que viene en la biblioteca ```wordcloud```, solo que no tiene soporte para el idioma español. Por ello vamos a utilizar la biblioteca ```stop_words```.
> To eliminate empty words, which are those that do not have their own meaning, you can use the ```STOPWORDS``` function that comes in the ```wordcloud``` library, only it does not have support for the Spanish language. So we are going to use the ```stop_words``` library.
Si no se tiene se puede instalar con el siguiente comando.
> If you don't have it, you can install it with the following command.
```shellscript
pip3 install stop-words
```
Para utilizar las stopwords, se coloca la biblioteca con la función a utilizar.
> To use stopwords, the library is placed with the function to use.
```python
from stop_words import get_stop_words
```
Para agrupar las stopwords en inglés y español, se puede hacer lo siguiente (se tienen dos variantes de asignación).
> To group the stopwords in English and Spanish, you can do the following (there are two assignment variants).
```python
sw_en = get_stop_words('en')
sw_en = get_stop_words('english')
```
```python
sw_es = get_stop_words('es')
sw_es = get_stop_words('spanish')
```
Concatenamos las stopwords en español y en inglés.
> We concatenate stopwords in Spanish and English
```python
stopwords = sw_en + sw_es
```
Por último, dentro del código en la función ```WordCloud()```, definimos las stopwords.
> Finally, within the code in the ```WordCloud()``` function, we define the stopwords.
```python
wordcloud = WordCloud(stopwords = stopwords)
```

Para probar la biblioteca se utilizó un trozo del texto de mi [post](https://peakd.com/hive-148441/@mtzrene/hola-a-todos-or-hi-everybody) de presentación en la comunidad hive
> ¡Hola mundo!, Mi nombre es René Martínez, nací en México, específicamente en la ciudad que capturó el sol Mexicali Baja California, pero ahora, por cuestiones académicas que ya se convirtieron en gusto y trabajo, vivo en la cenicienta del pacífico, Ensenada Baja California.
Hello! My name is René Martínez. I was born in Mexico, specifically in the city that captured the sun Mexicali Baja California, but now, for academic reasons that have already become comfort and live work in the Cinderella of the Pacific, Ensenada Baja California.
El contraste entre estas ciudades es muy grande a pesar de que solo están separadas por 250 Km. Por un lado tenemos un clima extremadamente desértico (Mexicali) con temperaturas de hasta 52° en verano y por otro lado un clima subtropical (Ensenada) con un mar frío. Sinceramente en ocasiones extraño el calor, pero salgo a tomar el aire, lo siento fresco y se me olvida.
The contrast between these cities is very high, although they are only 250 km away. On the one hand, we have an extreme desert climate (Mexicali) with temperatures of up to 52 ° in summer and, on the other side, a subtropical environment (Ensenada) with a cold sea. Honestly, sometimes I miss the heat, but I go out for air, I feel fresh and forget it.

## Código con stopwords | Code with stopwords
```python
from wordcloud import WordCloud
from stop_words import get_stop_words
sw_en = get_stop_words('en')
sw_es = get_stop_words('es')
stopwords = sw_en + sw_es
textwc = ""
with open('presentacion.txt', encoding='utf-8') as f:
textwc = ''.join(f.readlines())
wordcloud = WordCloud(font_path = "/usr/share/fonts/truetype/andika/Andika-R.ttf",
width = 4000,
height = 2000,
mask = None,
color_func = None,
max_words = 300,
min_font_size = 12,
stopwords = stopwords,
background_color = "gray",
max_font_size = 300,
colormap = "gist_heat",
contour_width = 0,
contour_color = "white")
wordcloud.generate(textwc)
wordcloud.to_file('presentacion.png')
```
#### Nube de palabras con stopwords | Wordcloud with stopwords

### Nube de palabras sin stopwords | Wordcloud without stopwords

A lo mejor es complicado de identificar por el gran número de palabras, pero en la segunda imagen podemos ver que al menos las palabras como "el", "ya", "un", "con", "on", entre otras, ya no parecen.
> Maybe it is difficult to identify due to a large number of words, but in the second image, we can see that at least the words like "el", "ya", "un", "con", "on", among others, no longer seem.

# Espero les haya gustado, ¡nos vemos en la segunda parte!
> # I hope you liked it, see you in the second part!

### Referencias | References
1. [https://hive.io/](https://hive.io/)
2. [https://pypi.org/project/stop-words/](https://pypi.org/project/stop-words/)
3. [https://matplotlib.org/](https://matplotlib.org/)
4. [https://amueller.github.io/word_cloud/index.html](https://amueller.github.io/word_cloud/index.html)