Create a Word Cloud in Python

1.1k Views Asked by At

I'm trying to create a Word Cloud Generator that displays the words from my collected data using python. The code here reads the data from my file (raw_data6) and display the word cloud, however, I'm asking if there's a possibility to create a search box so that the user will enter a word and search, and then the word cloud will display all the words related to the user search.

So basically, when the user will search a word for example (Poverty) in the search box, the word cloud will show all the words related to poverty.

My questions here: if this is possible, what is the code to implement this?

from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt #to display our wordcloud
from PIL import Image #to load our image
import numpy as np #to get the color of our image

text = open('../input/data-try/raw_data6.csv', mode="r", encoding="utf-8").read()
stopwords = set(STOPWORDS)

custom_mask = np.array(Image.open('../input/twitterpic/Twitter-PNG-Image.png'))
wc = WordCloud(background_color="white",
               stopwords=stopwords,
               mask = custom_mask,
              )
wc.generate(text)
image_colors = ImageColorGenerator(custom_mask)
wc.recolor(color_func = image_colors)

plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.show()

Here is a display of the word cloud after running the code above.

1

There are 1 best solutions below

2
Akshat Patel On

Try this once:

import matplotlib.pyplot as plt
from wordcloud import WordCloud
import numpy as np
import pandas as pd
import re

text = open('/home/student/Desktop/Python/Data/lyrics.txt', 'r').read()
stopwords = set(open('/home/student/Desktop/Python/Data/stopwords.txt', 'r').read().split())

custom_mask = np.array(Image.open("/home/student/Desktop/Python/Data/mask.png"))
wc = WordCloud(background_color="white", max_words=2000, mask=custom_mask, stopwords=stopwords)

wc.generate(text)
image_color = ImageColorGenerator(custom_mask)
wc.recolor(color_func=image_color)

plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()

You can change your path as your wish