У меня есть генератор wordcloud, который я использую в ноутбуке Jupyter.Я хотел бы создать для него внешний интерфейс, чтобы вы могли вставить текст в текстовое поле, нажать кнопку «Отправить», и он отобразит слово «облако».В основном то, что сделал этот глава здесь .
Я ищу некоторую помощь в изменении моего кода, чтобы вместо отображения wordcloud в записной книжке Jupyter он отображал изображение wordcloudна странице HTML.Я использую Django для создания внешнего интерфейса.
Это код, который у меня есть, который генерирует образ моего облака слов в моей записной книжке Jupyter.
from wordcloud import WordCloud
from PIL import Image
import matplotlib.pyplot as plt
import nltk
# sun only once -> nltk.download('punkt')
#nltk.download('wordnet') -> only do this once
from nltk.stem.porter import PorterStemmer
from nltk.stem import WordNetLemmatizer
ps = PorterStemmer()
wnl = WordNetLemmatizer()
def stem(string):
stemstring = ""
nltk_tokens = nltk.word_tokenize(string)
for word in nltk_tokens:
if word in dontstem:
p = word
elif word == 'printing':
p = 'print'
elif word == 'e-mailing':
p = 'email'
elif word == 'e-mails':
p = 'email'
elif word == 'e-mail':
p = 'email'
elif word == 'installation':
p = 'install'
#If the lemmatized word ends in a 'e' then lemmatize instead of stem as stem cuts the 'e'.
elif wnl.lemmatize(word).endswith('e'):
p = wnl.lemmatize(word)
elif wnl.lemmatize(word).endswith('y'):
p = wnl.lemmatize(word)
elif wnl.lemmatize(word).endswith('er'):
p = wnl.lemmatize(word)
elif wnl.lemmatize(word).endswith('ing'):
p = wnl.lemmatize(word)
else:
p = ps.stem(word)
stemstring += p + ' '
return stemstring
#We use a srt.split() to only count whole words as we don't want to count words inside words. This can happen below.
def count_substring(string,sub_string):
count=0
for word in string.split():
if word == sub_string:
count+=1
return(count)
#As we have a phrase which can be made up of two words we use this counting method as it is unlikely that the phrase is contained in another word.
def count_substring_phrases(string,sub_string):
count=0
for i in range(len(string)-len(sub_string)+1):
if(string[i:i+len(sub_string)] == sub_string ):
count+=1
return(count)
#The function for counting all the words
def countWords(string, phrases, stopWords, dostem):
newList = {}
for p in phrases:
if count_substring_phrases(string,p) > 0:
newList[p] = count_substring_phrases(string,p)
string = string.replace(p,'')
else:
pass
if dostem == True:
string = stem(string)
for word in string.split():
if word in stopWords:
pass
#Hack to exclude any word under 4 characters.
elif len(word) < 2:
pass
else:
count_substring(string,word)
newList[word] = count_substring(string,word)
return(newList)
MyData= dict(countWords(text, phrases, stopWords, True))
wc = WordCloud(scale=10, max_words=100).generate_from_frequencies(MyData)
plt.figure(figsize=(32,18))
plt.imshow(wc, interpolation="bilinear", aspect='auto')
plt.show()
Вот мой файл views.py.Как видите, я могу получить значение из поля формы и отправить его обратно на страницу.Теперь мне нужно получить значение из поля формы, запустить его через функцию wordcloud, сгенерировать изображение wordcloud, а затем отправить его обратно на страницу, чтобы я мог его отобразить.
from django.shortcuts import render
from wordcloudgen.forms import CharForm
from wordcloudgen.wordcloud import *
def cloud_gen(request):
if request.method == 'POST':
form = CharForm(request.POST)
if form.is_valid():
text = form.cleaned_data['post']
phrases = ''
stopWords = ''
args = {'form':form, 'text':text}
return render(request, 'wordcloudgen/cloud_gen.html', args)
else:
form = CharForm()
return render(request, 'wordcloudgen/cloud_gen.html', {'form':form})
Я бы подумал, что мне нужно что-то изменить в коде wordcloud где-то здесь:
MyData= dict(countWords(text, phrases, stopWords, True))
wc = WordCloud(scale=10, max_words=100).generate_from_frequencies(MyData)
plt.figure(figsize=(32,18))
plt.imshow(wc, interpolation="bilinear", aspect='auto')
plt.show()
, а затем добавить что-то в представление для вызова функции wordcloud, сохранить изображение, которое он выводит, и передать его моемупеременная args, так что я могу вызывать его в шаблоне HTML с чем-то вроде {% image%}.
Примечания: На данный момент некоторые аргументы в функции countWords жестко запрограммированы в пустые строки.Прямо сейчас есть только одно поле ввода в форме, которое будет для текста, когда у меня все работает, я тогда пойду и добавлю входные данные для всех других аргументов и опций, размеров графика для вывода и т. Д.
Спасибо