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

Words
523
Reading
3 min
Listen
Play
6y

!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
Como crear una nube de palabras con Python - Parte 2 | How to creat... | Ecency