Skip to content

Instantly share code, notes, and snippets.

@Eclectikus
Created December 27, 2020 14:38
Show Gist options
  • Save Eclectikus/23d00720935b428ea46e129ac028858b to your computer and use it in GitHub Desktop.
Save Eclectikus/23d00720935b428ea46e129ac028858b to your computer and use it in GitHub Desktop.
Discurso de Felipe VI - Nube de palabras - Código Python
# Nube de palabras para el discurso navideño del Rey 2020
# Versión BETA
import numpy as np
import os
from os import path
from PIL import Image
import matplotlib.pyplot as plt
import nltk # Natural Language Toolkit -> https://www.nltk.org/
from nltk.corpus import stopwords
nltk.download('stopwords')
from wordcloud import WordCloud, STOPWORDS # Generador de nubes de palabras para Python -> https://github.com/amueller/word_cloud
# Función de coloreado de palabras
def colores(
word=None,
font_size=None,
position=None,
orientation=None,
font_path=None,
random_state=None):
# Formato de color *hsl* - Ver por ejemplo: https://hslpicker.com/
h = 210
s = 90
l = int(90.0 * float(random_state.randint(90, 150)) / 255.0)
return "hsl({}, {}%, {}%)".format(h, s, l)
d = os.path.abspath(os.getcwd()) # Obtención directorio local
file_content=open(path.join(d,"rey2020.txt"), encoding="utf8", errors='ignore').read() # Lectura de fichero de texto
# corona_mask = np.array(Image.open(path.join(d, "mask_corona.png"))) # Lectura de imagen de máscara
corona_mask = np.array(Image.open(path.join(d, "mask_coronavirus.png"))) # Lectura de imagen de máscara
wcr = WordCloud(font_path = r'C:\Windows\Fonts\BRITANIC.TTF', # Utiliza la fuente que desees usando el directorio apropiado
mask = corona_mask,
stopwords = stopwords.words('spanish'),
background_color = 'black',
width = 3000,
height = 1800,
color_func = colores
)
wcr.generate(file_content)
# plt.figure(figsize=(180,90)) # ~ Resolución
plt.figure()
plt.imshow(wcr, interpolation="bilinear")
plt.axis("off")
plt.margins(x=0, y=0)
plt.savefig('rey2020.png', facecolor='k', bbox_inches='tight')
plt.show()
@Eclectikus
Copy link
Author

Eclectikus commented Dec 27, 2020

El resultado se puede ver en éste tuit.

Está el modelo Corona estándar:

Nube de palabras del discurso de Felipe VI 2020 - Corona

Y el modelo Coronavirus:

Nube de palabras del discurso de Felipe VI 2020 - Coronavirus

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment