使用streamlit上线中文文本分析网站

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-16 22:50   11   0

cnsenti App

这是使用streamlit库将中文情感分析[cnsenti 部署到网络世界,可在线提供简单的中文文本的情绪及情感计算

streamlit库(https://docs.streamlit.io/en/stable/), 是目前简单易用的数据可视化web框架,比flask和django少了很多的扩展性,但是容易学习上手,适合初学者把玩。
文末有代码可供下载

网址[1]

使用教程 [2]点击下方观看视频

网站

现在技术有限,该网站大致内容分为三部分

准备数据数据分析情感分析词云图谢谢支持

本地使用

本网站的cnsentiDemo项目文件夹的文件有

- main.py
- cnsenti_example.csv
- 大邓和他的Python.png
- requirements.txt
- 其他文件

将cnsentiDemo项目下载,在电脑本地离线使用cnsenti的方法

1.下载解压到桌面desktop2.命令行, 执行 cd desktop/cnsentiDemo3.命令行,执行 pip3 install -r requirements.txt4.命令行, 执行 streamlit run main.py5.根据命令行的提示,复制粘贴网址到桌面。我这里是 **http://localhost:8501**6.浏览器打开效果就会与视频等同

上述过程中,Mac和Win会有一些缺点导致无法使用,需要根据命令行提示解决各自系统的小问题,例如

1.Win需要使用64位的Python2.Mac可能需要安装Xcode-install3.其他可能的问题

main.py文件

import streamlit as st
import pandas as pd
from cnsenti import Emotion, Sentiment
import jieba
import re


st.title("cnsenti App")
st.markdown("""
*这是中文情感分析**[cnsenti库](https://github.com/thunderhit/cnsenti) **对应的测试网站,可以提供简单中文文本的情绪及情感计算。*
""")




st.title('准备数据')
uploaded_file = st.file_uploader(label='可以对自有的CSV文件进行上传、分析情感、制作词云图', type=['csv'])
st.markdown("""
**注意: **上传前请参考[**CSV示例**](https://raw.githubusercontent.com/thunderhit/cnsenti/master/test/cnsenti_example.csv),将数据文件改为字段名为 **text**, 编码方式为 **UTF-8** 的 CSV 
    """)




@st.cache(suppress_st_warning=True)
def wordfreqs_count(uploaded_file='cnsenti_example.csv'):
    df = pd.read_csv(uploaded_file)
    df.drop_duplicates(inplace=True)
    df.dropna(inplace=True)
    text = ''.join(re.findall('[\u4e00-\u9fa5]+', ''.join(df['text'])))
    wordfreqs = dict()
    #for idx, text in enumerate(df['text']):
    words = jieba.lcut(text)
    wordset = set(words)
    for word in wordset:
        wordfreqs.setdefault(word, 0)
        wordfreqs[word] = wordfreqs[word] + words.count(word)
    res = [(k, v) for k,v in wordfreqs.items() if v>1 and len(k)>1]
    return res




def gen_wordcloud(wordfreqs):
    from pyecharts import options as opts
    from pyecharts.charts import WordCloud
    from streamlit_echarts import st_pyecharts
    b = (
        WordCloud()
        .add(series_name='WordCloud', data_pair=wordfreqs, word_size_range=[6, 66])
        .set_global_opts(
        title_opts=opts.TitleOpts(
            title="",
            title_textstyle_opts=opts.TextStyleOpts(font_size=23))
            )
        )
    return st_pyecharts(b)






st.title('数据分析')
st.write('\n\n\n\n')
wc = st.button(label='词云图')
try:
    wordfreqs = wordfreqs_count(uploaded_file=uploaded_file)
except:
    wordfreqs = wordfreqs_count()
if wc == True:
    st.balloons()
    gen_wordcloud(wordfreqs=wordfreqs)




@st.cache(suppress_st_warning=True)
def measure(uploaded_file='cnsenti_example.csv'):
    df = pd.read_csv(uploaded_file)
    df.drop_duplicates(inplace=True)
    df.dropna(inplace=True)
    sentiment = Sentiment()
    emotion = Emotion()
    sensentiment_res = df['text'].apply(sentiment.sentiment_count).apply(pd.Series)
    emotion_res = df['text'].apply(emotion.emotion_count).apply(pd.Series)
    sentiment_result = pd.concat([df, sensentiment_res], axis=1)
    emotion_result = pd.concat([df, emotion_res], axis=1)
    return sentiment_result,emotion_result




senti = st.button(label='情感计算')
try:
    sentiment_result , emotion_result= measure(uploaded_file=uploaded_file)
except ValueError as e:
    sentiment_result, emotion_result = measure()
if senti==True:
    st.balloons()
    st.markdown('**Sentiment Result**')
    st.write(sentiment_result)
    st.markdown('**Emoion Result**')
    st.write(emotion_result)




st.markdown("""
# 谢谢支持
- [**腾讯课堂: Python网络爬虫与文本分析**](https://ke.qq.com/course/482241?tuin=163164df)
- [**B站:大邓和他的python**](https://space.bilibili.com/122592901/channel/detail?cid=66008)
- [**github: DaDeng**](https://github.com/thunderhit)
- **公众号:大邓和他的python**
""")
st.image('大邓和他的Python.png')

Web部署方法

如果想将自己的streamlit项目部署成网站,可以使用Heroku和github帮助你完成人生第一个小网站。操作方法:

1.将写好的streamlit项目上传至github自有仓库2.Heroku注册账号3.点击Heroku网页右上角New, 选择Create new app4.绑定github,连接github里的streamlit项目5.部署

部署方法也可参考 Youtube视频[3]

项目源代码请点击阅读原文

References

[1] 网址: https://cnsenti.herokuapp.com/
[2] 使用教程 : https://www.bilibili.com/video/bv17V411H7sZ
[3] Youtube视频: https://www.youtube.com/watch?v=zK4Ch6e1zq8&list=PLtqF5YXg7GLmCvTswG32NqQypOuYkPRUE&index=5

精选文章系列视频|Python网络爬虫与文本数据分析
B站视频 | Python自动化办公

SciencePlots | 科研样式绘图库
bsite库 | 采集B站视频信息、评论数据

texthero包 | 支持dataframe的文本分析包
爬虫实战 | 采集&可视化知乎问题的回答
pdf2docx库 | 转文件格式,支持抽取文件中的表格数据
rpy2库 | 在jupyter中调用R语言代码
tidytext | 耳目一新的R-style文本分析库
reticulate包 | 在Rmarkdown中调用Python代码
plydata库 | 数据操作管道操作符>>
plotnine: Python版的ggplot2作图库

七夕礼物 | 全网最火的钉子绕线图制作教程

读完本文你就了解什么是文本分析

文本分析在经管领域中的应用概述  
综述:文本分析在市场营销研究中的应用

plotnine: Python版的ggplot2作图库
小案例: Pandas的apply方法  
stylecloud:简洁易用的词云库 
用Python绘制近20年地方财政收入变迁史视频  
Wow~70G上市公司定期报告数据集

漂亮~pandas可以无缝衔接Bokeh  
YelpDaset: 酒店管理类数据集10+G  


“分享”和“在看”是更好的支持

项目源代码请点击阅读原文

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP