amueller / word_cloud

A little word cloud generator in Python
https://amueller.github.io/word_cloud
MIT License
10.01k stars 2.31k forks source link

Custom and radom Font Size #731

Open MarleneBs opened 11 months ago

MarleneBs commented 11 months ago

I have the following issue: I have an existing code that creates a word cloud, and it works fine. The initial problem is that the sizes of the words are not randomly distributed; the first word I input ends up the largest, and then it decreases in size. However, I'd like the sizes to be randomly assigned. Now, I want to modify my code to set specific font sizes for a few selected words while keeping the rest of the words randomly distributed. I want to ensure that the other functionalities of my code remain intact. In other words, each word should still appear exactly once, and the use of the mask, colors, and font should remain unchanged.

This is my Code:

import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from PIL import Image

text = "Python  Analyse Hallo "
zweiteilige_woerter = {"Hallo DU", "Deep Learning", "Netzszenarien"}

frequencies = {}
for word in text.split():
    frequencies[word] = frequencies.get(word, 0) + 1

# Verarbeite die Wörter aus der Menge der zweiteiligen Wörter und setze ihre Häufigkeiten in frequencies
for word in zweiteilige_woerter:
    frequencies[word] = frequencies.get(word, 0) + 1

# Erstelle eine quadratische Maske in der gewünschten Größe
width_px = 800
height_px = 800
x, y = np.ogrid[:width_px, :height_px]
mask = (x - width_px//2) ** 2 + (y - height_px//2) ** 2 > (width_px//2) ** 2
mask = 255 * mask.astype(int)

wordcloud = WordCloud(background_color=None, mode="RGBA", contour_color='white', contour_width=0, prefer_horizontal=1.0, font_path='arial', mask=mask, max_font_size=80)

wordcloud.generate_from_frequencies(frequencies=frequencies)

colors = [(100, 30, 10), (0, 0, 0)]   #example, I used different colors, but this is just the kind of 

def random_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None):
    return colors[np.random.randint(0, len(colors))]

# Wende die Farben auf die WordCloud an
wordcloud.recolor(color_func=random_color_func)

# Zeige die WordCloud an
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

I tried multiple ways with CHatGBT to change my Code in the way I discribed, but I nothing worked. Greetings Marlene