Como crear una nube de palabras con Python - Parte 2 | How to create a word cloud with Python - Part 2

in #spanish4 years ago (edited)

!Hola¡ | ¡Hello!

En la parte 1, aprendieron a como crear una nube de palabras sencilla y elaborada modificando ciertos parámetros. En esta segunda parte aprenderán a crear nubes de palabras utilizando una imagen como máscara. Para este ejemplo tomé la siguiente imagen de hive.

In Part 1, they learned how to create a simple and elaborate word cloud by modifying specific parameters. In this second part, you will learn how to create word clouds using an image as a mask. For this example, I took the following hive image.

Mex Source

sable_doble.png

Para usar una imagen como máscara, es recomendable que esté en formato .png y con fondo transparente. Además es necesario utilizar la biblioteca NumPy y la función Image() de la biblioteca PIL. Para esto, en el código vamos a agregar las siguientes líneas.

To use an image as a mask, it recommended that it be in .png format and with a transparent background. Also, it is necessary to use the NumPy library and the Image() function of the PIL library. For this, in the code, we are going to add the following lines.

from PIL import Image
import numpy as np

Con PIL, se abre y carga la imagen, y con NumPy, se convierte en una matriz. Traducido a código queda de la siguiente forma.

With PIL, the image is opened and loaded, and with NumPy, it becomes an array. Translated into code is as follows.

mask = np.array(Image.open("hive.png"))

Esta línea de código es importante anteponerla a las líneas con las que generamos la nube de palabras, que se muestran a continuación.

This line of code is essential to put it before the lines with which we generate the wordcloud, shown below.

wordcloud = WordCloud(mask = mask, 
                      stopwords = stopwords)
wordcloud.generate(textwc)
wordcloud.to_file('wc_mask.png')

Y con estas adiciones podemos generar nubes de palabras usando imágenes como contorno. A continuación les presento el código completo y el resultado obtenido.

And with these additions, we can generate word clouds using images as an outline. Below I present the complete code and the result obtained.

sable_doble.png

Código completo y resultado | Complete code and result

Como texto para este ejemplo, se utilizaron los nombres de varias comunidades y usuarios de Hive.

As the text for this example, the names of various Hive communities and users used.

from wordcloud import WordCloud
from stop_words import get_stop_words
from PIL import Image
import numpy as np

sw_en = get_stop_words('en')
sw_es = get_stop_words('es')
stopwords = sw_en + sw_es

textwc = ""

with open('hive.txt', encoding='utf-8') as f:
    textwc = ''.join(f.readlines())

mask = np.array(Image.open("hive.png"))
wordcloud = WordCloud(mask = mask, 
                      stopwords = stopwords)

wordcloud.generate(textwc)

wordcloud.to_file('wc_mask.png')

wc_mask.png

sable_doble.png

Código con modificaciones y resultado | Code with modifications and result

from wordcloud import WordCloud
from stop_words import get_stop_words
from PIL import Image
import numpy as np

sw_en = get_stop_words('en')
sw_es = get_stop_words('es')
stopwords = sw_en + sw_es

textwc = ""

with open('hive.txt', encoding='utf-8') as f:
    textwc = ''.join(f.readlines())

mask = np.array(Image.open("hive.png"))
wordcloud = WordCloud(mask = mask, 
                      stopwords = stopwords,
                      background_color = "black", #or white
                      color_func = lambda *args, **kwargs: "gray", #or black
                      contour_width = 4,
                      contour_color = "red")

wordcloud.generate(textwc)

wordcloud.to_file('wc_mask-mod.png')
wc_maskmod.pngwc_maskmod_1.png

sable_doble.png

Utilizando el color de la imagen máscara | Using the mask image color

Si la imagen que estás utilizando como máscara tiene color, puedes usar sus colores para colorear tu nube de palabras. ¿Cómo haré eso?, sencillo, utilizando la función ImageColorGenerator() y recolor() de la biblioteca worcloud.

If the image you are using as a mask has color, you can use its colors to color your word cloud. How will I do that ?, simple, using the ImageColorGenerator() and recolor() functions from the worcloud library.

from wordcloud import WordCloud, ImageColorGenerator

Después de la generación de la nube de palabras, solo debes agregar estas líneas de código.

After the wordcloud generation, add these lines of code.

colors = ImageColorGenerator(mask)
wordcloud.recolor(color_func = colors)

sable_doble.png

Código completo y resultado | Complete code and result

from wordcloud import WordCloud, ImageColorGenerator
from stop_words import get_stop_words
from PIL import Image
import numpy as np

sw_en = get_stop_words('en')
sw_es = get_stop_words('es')
stopwords = sw_en + sw_es

textwc = ""

with open('hive.txt', encoding='utf-8') as f:
    textwc = ''.join(f.readlines())

mask = np.array(Image.open("hive.png"))
wordcloud = WordCloud(mask = mask, 
                      stopwords = stopwords,
                      #background_color = "white",
                      #contour_width = 2, 
                      #contour_color = 'red'
                      )

wordcloud.generate(textwc)

colors = ImageColorGenerator(mask)
wordcloud.recolor(color_func = colors)

wordcloud.to_file('wc_maskcolor.png')

wc_maskcolor.png

Imágenes con modificaciones | Images with modifications

wc_maskcolor1mod.pngwc_maskcolormod.png

sable_doble.png

¡Gracias por leer mi post, espero les haya agradado!

Thanks for reading my post. I hope you liked it!

sable_doble.png

Referencias | References

  1. https://hive.io/
  2. https://pypi.org/project/stop-words/
  3. https://matplotlib.org/
  4. https://amueller.github.io/word_cloud/index.html
Sort:  

Thanks for sharing well prepared tutorial about the word cloud with python in two languages. We are looking for people like you in our community.

Your post has been submitted to be curated with @gitplait community account because this is the kind of publications we like to see in our community.

Join our Community on Hive and Chat with us on Discord.

[Gitplait-Team]

Congratulations @mtzrene! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

You received more than 300 upvotes. Your next target is to reach 400 upvotes.

You can view your badges on your board And compare to others on the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @hivebuzz:

The Hive community is in mourning. Farewell @lizziesworld!
Support the HiveBuzz project. Vote for our proposal!

Saludos. Gracias por compartir. Siempre me gusta probar los códigos y así voy aprendiendo. Traté de instalar "wordcloud" y me da error. Tengo windows 10, 64-bit y python 3.8.3. De todas maneras seguiré intentando, o tal vez puede ser el internet que ha estado deficiente por estos lares.

¿Estás utilizando Anaconda?, ¿qué error te sale?.

Yo recomiendo utilizar python 3.6 o 3.7.

Saludos. Gracias por estar pendiente. No estoy usando Anaconda. Cree un entorno virtual instalé las demás librerias bien, menos la de wordcloud.

Partes del error. Es mucho mas largo. seleccioné dos bloques
Using legacy setup.py install for wordcloud, since package 'wheel' is not installed.
Installing collected packages: wordcloud
Running setup.py install for wordcloud ... error

creating build\lib.win32-3.8
creating build\lib.win32-3.8\wordcloud
copying wordcloud\color_from_image.py -> build\lib.win32-3.8\wordcloud

UPDATING build\lib.win32-3.8\wordcloud/_version.py
set build\lib.win32-3.8\wordcloud/_version.py to '1.7.0'
Esto último sale en rojo
Me parece que es por lo del 64-bit de mi equipo

Ok, ya sé.

Baja la versión que necesites https://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud te vas al directorio y de ahí ejecuta.

python -m pip install

Espero funcione.

Gracias por tu amable atención!

Saludos nuevamente. La solución fue instalar python 3.7. Seguía dando error de instalación de la librería.

Aquí la prueba de que corrió a la perfección. Gracias por tu publicación he aprendido un nuevo tema y me animas a seguir aprendiendo cada día.

wc_mask.png

Mil gracias!

¡Excelente!, que gusto saber que funcionó.

A seguir aprendiendo que en este tema hay mucho que ver.

¡Saludos!