Я нашел этот Кернал на Kaggle здесь
Он генерирует облако слов над изображением Дональда Трампа, используя его твиты.
Трамп
Я хотел повторить это для Обамы и его твитов, чтобы узнать, как это работает, поскольку я действительно новичок в Python.
У меня проблемы с генерацией облака, которое хорошо соответствует изображению, и мне интересно, так ли это, потому что я неправильно адаптирую код или просто делаю неправильный выбор с моим изображением. Может кто-нибудь помочь мне получить красивое облако слов, где вы можете сказать, что это Обама?
Вот мой код, который я адаптирую:
Все это прекрасно работает, но я хотел бы включить его для справки:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 31 10:56:19 2020
@author: jordanwegner
"""
# Obama Tweets by Me. I am going to try and replicate the work done by
# Mikolaj Witkowski on the Trump Tweets
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from bs4 import BeautifulSoup
import requests
import re
from wordcloud import WordCloud
from PIL import Image
import random
import matplotlib.pyplot as plt
from matplotlib import cm
from nltk import regexp_tokenize
from nltk.corpus import stopwords
import nltk
from io import BytesIO
import urllib.request
from wordcloud import ImageColorGenerator
tweets = pd.read_csv('/Users/jordanwegner/Desktop/Kaggle/Obama Tweets/WHtweets.csv')
# Just the content of the tweets
content = tweets['text']
# Stopwords are words that do not have much meaning in a sentence
sw = stopwords.words('english')
patn = '\w+'
blacklist = [
'[document]',
'noscript',
'header',
'html',
'meta',
'via'
'head',
'input',
'solo',
'band',
'guitars',
'vocals',
'guitar',
'bass',
'song',
'writer',
'composed',
'composer',
'music',
'submit',
'site',
'request',
'ask',
'send',
'like',
'share',
'correcting',
'correct',
'correction',
'thank',
'thanks',
'you',
'more',
'http',
'realdonaldtrump',
'https',
'com',
'www',
'twitter',
]
# Does something to the strings
def data_cleanup(text):
text = text.lower()
text = re.sub(r'\[.*?\]', '', text)
text = re.sub(r'([.!,?])', r' \1 ', text)
text = re.sub(r'[^a-zA-Z.,!?]+', r' ', text)
text = regexp_tokenize(text, patn)
text = [i for i in text if (i not in sw) and (i not in blacklist)]
return text
clean_text = content.apply(lambda x: data_cleanup(x))
# I think just makes a vector of all the words in the content minus
# the words removed in earlier steps
words = []
for i in clean_text:
for j in i:
words.append(j)
word_freq = nltk.FreqDist([i for i in words if len(i) > 2])
plt.figure(figsize=(16, 6))
word_freq.plot(50)
Вот где слово Начинается проблема с облаком, и вот изображение, которое я использую:
исходное изображение
obama = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSds3CXs2QKhveQ7IkMnAINpAkqYG__KSxdaxlJ3IxMlPhtX8UG&usqp=CAU'
with urllib.request.urlopen(obama) as url:
f = BytesIO(url.read())
img = Image.open(f)
mask = np.array(img)
def transform_format(val):
if val ==0:
return 255
else:
return val
t_mask = np.ndarray((mask.shape[0], mask.shape[1]), np.int32)
for i in range(len(mask)):
t_mask[i] = list(map(transform_format, mask[i]))
img_color = ImageColorGenerator(t_mask)
def grey_color_func(word, font_size, position,orientation,random_state=None, **kwargs):
return("hsl(100, 5%%, %d%%)" % np.random.randint(0,50))
wc = WordCloud(background_color='white',
mask=t_mask,
max_font_size=2000,
max_words=2000,
random_state=42)
wcloud = wc.generate_from_frequencies(word_freq)
plt.figure(figsize=(16, 10))
# recolor wordcloud and show
# we could also give color_func=image_colors directly in the constructor
plt.axis('off')
plt.imshow(wc.recolor(color_func = grey_color_func), interpolation="bilinear")
plt.show()
Оно выплевывает это:
генерировать Обаму
Если бы не было Обамы, никто бы не смог сказать, кто это. С изображением Трампа это довольно очевидно, даже без большого «Трампа». Я хотел бы получить более четкое представление об Обаме.
Спасибо!
Джордан