您的位置:首页 > 编程语言 > Python开发

python3使用flask框架搭建在线词云应用

2017-08-03 20:16 756 查看
词云生成

词云生成调用了python中的几个功能强大的包,实现文本切割、图像处理和词云生成。

jieba

jieba是python中用于中文文本分词的模块,支持多种切分模式,并且可以自定义停用词表,去除无意义的词。
scipy

scipy是python中一个用于科学计算的包,其中的misc模块中提供了一些图像处理的函数,这里主要用了imread()和imsave()函数进行图像读取、二值化和存储。
wordcloud

wordcloud是一个词云生成的包,可以根据输入文本串生成词云图。
下面介绍代码(分词和词云生成):

分词采用python的jieba模块,实现文本清洗,分词和去停用词处理。

class word_spliter():
def __init__(self,text,stop_path = sw_path):
self.text = text
self.stop_word = stop_path

def get_stopword(self):
stopwords = {}.fromkeys([line.rstrip() for line in open(self.stop_word, encoding='utf-8')])
return stopwords

def text_wash(self):
self.text = self.text.encode(encoding="utf-8",errors='ignore').decode("utf-8")
# print(self.text)
return self.text

def split_word(self):
seq = ''
sw_words = self.get_stopword()
text = self.text_wash()
segs = jieba.cut(text,cut_all=False)
for seg in segs:
if seg not in sw_words:
seq = seq + seg +" "
return seq

词云生成需要指定一个字体路径,这里指定为./utils/msyh.ttc'

class wordclouder():
# get parameter
def __init__(self,text,image):
self.text = text
self.imag = image

# generate picture
def word_cloud(self):
mask_image = imread(self.imag,flatten=False)
word_pic = WordCloud(
font_path='./utils/msyh.ttc',
background_color='white',
mask=mask_image
).generate(self.text)
imsave(self.imag,word_pic)

flask框架

首先需要创建一个应用,然后添加下面的功能

路由

通过装饰器让url地址指向对应执行函数
重定向

从主地址跳转向upload
upload & download

完成图片&文字的上传,返回生成的词云图片
# Create the application.
APP = flask.Flask(__name__)

@APP.route('/',methods=['GET', 'POST'])
def index():
""" 显示可在 '/' 访问的 index 页面
"""
return redirect(url_for('upload'))

@APP.route('/upload',methods=['GET', 'POST'])
def upload():
err = None
if request.method == "POST":
pic = request.files['uploadPic']
text = request.form['wordStr']
pic_path = "./static/pic/"+pic.filename
pic.save(pic_path)
generate_wordcloud(text,pic_path)
response = make_response(send_file(pic_path))
response.headers["Content-Disposition"] = "attachment; filename=wordcloud.jpg;"
return response
# return flask.render_template('wordcloud.html',pic_name = 'pic/'+pic.filename)
else:
err = "post method required"
return  flask.render_template('upload.html',error=err)

以上操作就在本地基于python3和flask实现了一个在线的词云生成web应用,效果如图所示:

wordcloud.jpg

完整代码放到了github上:
https://github.com/hunterzju/flask_wordcloud

最后放两张用于生成词云的模版图片:

maks.jpg

mask2.jpg
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: