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

in HiveDevs4 years ago

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

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 entries.

hive_basic.png

sable_doble.png

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.

sable_doble.png

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:

pip3 install wordcloud

Si tienen anaconda, pueden usar el siguiente comando:

If they have anaconda, you can use the following command:

conda install -c conda-forge wordcloud

sable_doble.png

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.

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.

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.

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.

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().

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í. 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í.
  • 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. 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.
  • 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.

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.

wordcloud.to_file('hive.png')

sable_doble.png

Código básico completo | Complete basic code

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

hive_basic.png

sable_doble.png

Código modificado | Modified code

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

hive_mod.png

sable_doble.png

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.

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.

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).

sw_en = get_stop_words('en')
sw_en = get_stop_words('english')
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

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.

wordcloud = WordCloud(stopwords = stopwords)

sable_doble.png

Para probar la biblioteca se utilizó un trozo del texto de mi post 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.

sable_doble.png

Código con stopwords | Code with stopwords

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

presetacion_modswnone.png

Nube de palabras sin stopwords | Wordcloud without stopwords

presetacion_modsw.png

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.

sable_doble.png

Espero les haya gustado, ¡nos vemos en la segunda parte!

I hope you liked it, see you in the second part!

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:  

¡Felicitaciones!



Estás participando para optar a la mención especial de nuestra COMUNIDAD (Recompensa de 1 Hive), también has recibido 1 ENTROKEN.

1. Invierte en el PROYECTO ENTROPÍA y recibe ganancias semanalmente. Entra aquí para más información.

2. Contáctanos en Discord: https://discord.gg/hkCjFeb

3. Suscríbete a nuestra COMUNIDAD, apoya al trail de @Entropia y así podrás ganar recompensas de curación de forma automática. Entra aquí para más información sobre nuestro trail.

4. Creación de cuentas nuevas de Hive aquí.

5. Visita nuestro canal de Youtube.

Atentamente

El equipo de curación del PROYECTO ENTROPÍA

Amazing effort. Writting post in bi-language made your tutorial worthy for more people around the globe. Keep it up your good work.
Your post has been 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.

Thanks for the support.

¡Muchas gracias por el apoyo!

Quedó excelente, intentaré hacer una nube de letras en python para un concurso en Hive.
Gracias por compartir este tipo de publicaciones para los que vamos empezando a programar y entender como funciona python.

Saludos! 💪

Gracias por el apoyo.
Compártenos el resultado.

¡Saludos!

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

You received more than 100 upvotes. Your next target is to reach 200 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

To support your work, I also upvoted your post!

Support the HiveBuzz project. Vote for our proposal!