-
Notifications
You must be signed in to change notification settings - Fork 0
/
Wikipedia_Wordcloud.py
67 lines (47 loc) · 1.52 KB
/
Wikipedia_Wordcloud.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# coding: utf-8
# In[18]:
import wikipedia as wp
from wordcloud import WordCloud, STOPWORDS
from os import path
import numpy as np
from PIL import Image
def get_wiki(query):
title= wp.search(query, results=1)
page= wp.page(title)
return page.content
def printing_top_word_frequencies():
split_contents= contents.split(" ")
relevant_words= list(filter(lambda x: x not in STOPWORDS,split_contents))
word_count = dict()
for i in relevant_words:
if i in word_count.keys():
word_count[i]=word_count[i]+1
else:
word_count[i]=1
final_unique_values= sorted(set(list(word_count.values())),reverse=True)
print("Words appeared the most")
for y in final_unique_values[0:5]:
for (a,b) in word_count.items():
if b==y:
print((a,b))
# In[ ]:
if __name__ == "__main__":
search_term=input("Enter the search term to form a wordcloud for: ")
contents=get_wiki(search_term)
printing_top_word_frequencies()
create_wordcloud(contents)
# In[17]:
def create_wordcloud(text):
# create numpy araay for wordcloud mask image
mask = np.array(Image.open(path.join("cloud.png")))
# create set of stopwords
stopwords = set(STOPWORDS)
# create wordcloud object
wc = WordCloud(background_color="white",
max_words=200,
mask=mask,
stopwords=stopwords)
# generate wordcloud
wc.generate(text)
# save wordcloud
wc.to_file(path.join("wc.png"))