vue 精选评论词云 集成echarts-wordcloud TF-IDF算法

本文主要是介绍vue 精选评论词云 集成echarts-wordcloud TF-IDF算法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

这一期在我们的系统里集成词云组件,开发的功能是景区精选评论的词云展示功能。

这个界面的逻辑是这样的:

在数据框里输入城市,可以是模糊搜索的,选择城市;

选择城市后,发往后台去查询该城市的精选评论,由于一个城市会有很多景点,所以精选评论也有很多,采用TF-IDF算法,计算关键词,返回给前端,使用echarts词云组件进行可视化;

再次输入城市,可以切换城市,同时词云会重新渲染。

1 词云页面开发

首先前端安装词云,(注意这边的echarts必须是v5+,如果是4就要使用echarts-wordcloud 1.0版本)

npm install echarts-wordcloud@2

然后在main.js中引入

Vue.component('v-chart', ECharts);
import "echarts-wordcloud"

创建一个WordCloud.vue组件,组件的高度和数据从外部传入

<template><v-chartstyle="width:100%; ":option="chartOption":style="{ height: height }"autoresize/>
</template><script>export default {name: 'WordCloud',props: {words: {type: Array,required: true},height: {type: String,required: true},},watch: {words: {immediate: true,handler() {this.initChart();}}},data() {return {chartOption: {},maskImage: new Image(),data: [],};},async mounted() {// this.initChart()},methods: {initChart() {// this.maskImage.src = require('@/assets/rensen.png')console.log('init wordcloud...')console.log(this.words)setTimeout(() => {this.chartOption = this.buildChartOption();// console.log(this.chartOption)}, 1000)},buildChartOption() {// console.log(this.maskImage)const option = {// background: '#FFFFFF',tooltip: {formatter: '{b}<br/> 出现频次:{c}  '},series: [ {// maskImage: this.maskImage,type: 'wordCloud',gridSize: 2,sizeRange: [20, 80],// shape: 'heart',layoutAnimation: true,textStyle:{textBorderColor: 'rgba(255,255,255,0.3)',textBorderWidth: 1,color: ()=>{return 'rgb(' + [Math.round(Math.random() * 160),Math.round(Math.random() * 160),Math.round(Math.random() * 160)].join(',') + ')';},emphasis: {fontSize: 20,shadowBlur: 10,shadowColor: 'rgba(255,255,255,.1)'}},data: this.words} ]};return option;},}
};
</script>

创建Word.vue 词云组件页面,这个组件集成了el-autocomplete组件,可以远程搜索城市,这个在上一篇博文里有说过怎么开发了,这边主要是集成WordCloud.vue组件,通过get_wordcloud 方法来从后端加载精选评论词频分析数据。

<template><div><el-row :gutter="20"><!-- 输入框放在图表上方 --><el-autocompletev-model="city":fetch-suggestions="querySearch"placeholder="请输入城市名称"@select="handleSelect"style="width: 300px; margin-left: 10px;"clearable></el-autocomplete><!-- Top chart --><el-col :span="24"><div class="chart" :style="{ height: parentHeight }"><word-cloud :height="childHeight" :words="words"/></div></el-col></el-row></div>
</template><script>
import {getCities, get_wordcloud} from "@/api/tour";
import WordCloud from "@/components/WordCloud.vue";export default {name: 'Dashboard',data(){return{city: '',words: [],}},components: {WordCloud},mounted() {get_wordcloud(this.city).then(res=>{this.words = res.data.data})},computed: {parentHeight() {return `calc(100vh - 140px)`; // 父组件高度},childHeight() {return `calc(100vh - 140px)`; // 子组件高度}},methods: {// el-autocomplete组件的cb 为回调函数需要把后端返回的值传给它querySearch(queryString, cb) {// 发送请求到Flask后端获取模糊搜索结果getCities(queryString).then(res=>{// console.log(res.data.data.map(i=>{return i.value}))cb(res.data.data)})},// el-autocomplete组件选择handleSelect(item) {this.city = item.value; // 选择后将城市名存储在city变量中console.log('选择了:', this.city);this.$message('加载'+this.city+'数据成功', 'success', 3000)get_wordcloud(this.city).then(res=>{this.words = res.data.data})},},
};
</script><style scoped>
.chart {/*display: flex;*/align-items: center;justify-content: center;margin-top: 10px;color: white;font-size: 20px;border-radius: 10px;background-color: #f4eeee;
}
</style>

添加一个方法:

// 词云
export function  get_wordcloud(keyword){return request({url: `/tour/wordcloud`,method: 'get',params:{ keyword: keyword }});
}

2 后端接口开发

后端接口根据前端传递过来关键词去查询该城市下的所有精选评论数据,然后使用jieba分词进行中文分析,过滤2个字以下的内容,然后创建TF-IDF向量化器计算每个词的TF-IDF词,排序之后,获取前100的重要词返回给前端。

# 词云接口
@main.route('/tour/wordcloud', methods=['GET'])
def get_wordcloud():keyword = request.args.get('keyword', '')if keyword=='':keyword = '东京'try:# 查询符合条件的 Tourcomments = db.session.query(Tour.select_comment).filter(Tour.city == keyword).all()# 提取评论文本comments_text = [comment[0] for comment in comments if comment[0] is not None]# 使用 jieba 分词def jieba_tokenizer(text):return [word for word in jieba.cut(text) if len(word) >= 2]# 创建 TF-IDF 向量化器vectorizer = TfidfVectorizer(tokenizer=jieba_tokenizer, stop_words=None)  # 可以根据需要添加停用词tfidf_matrix = vectorizer.fit_transform(comments_text)# 获取词汇表feature_names = vectorizer.get_feature_names_out()# 计算每个词的 TF-IDF 值tfidf_sum = tfidf_matrix.sum(axis=0).A1  # 将稀疏矩阵转换为数组tfidf_dict = dict(zip(feature_names, tfidf_sum))# 按 TF-IDF 值排序,提取前 100 个重要词sorted_tfidf = sorted(tfidf_dict.items(), key=lambda x: x[1], reverse=True)[:100]# TF-IDF 值 取整了top_100_words = [{"name": word, "value": int(score)} for word, score in sorted_tfidf]# print(top_100_words)return make_response(code=0, data=top_100_words)except Exception as e:return make_response(code=1, message=str(e))

3 效果

3.1 东京景区评论词云

在这里插入图片描述

3.2 可以搜索选择其他城市

在这里插入图片描述

3.3 切换城市,例如名古屋

在这里插入图片描述

4 补充TF-IDF介绍

TF-IDF(Term Frequency-Inverse Document Frequency)是一种用于信息检索和文本挖掘的权重计算方法。 它旨在评估一个词在一篇文档中的重要性,具体而言:

1. **词频(Term Frequency, TF)**:表示一个词在文档中出现的频率。频率越高,表示该词对文档的贡献越大。

2. **逆文档频率(Inverse Document Frequency, IDF)**:表示一个词在所有文档中的稀有程度。IDF 值通过总文档数除以包含该词的文档数,然后取对数来计算。# - 公式为 IDF(w) = log(总文档数 / (包含词 w 的文档数 + 1))# - 一个常见的词(如“的”、“是”)在许多文档中出现,IDF 值较低,表示它的区分能力弱。#

3. **TF-IDF 值**:通过将词频和逆文档频率相乘得到。TF-IDF 值高的词在特定文档中重要性较高,且在其他文档中较少出现。## 在文本分析中,TF-IDF 常用于特征提取,以帮助识别关键词和主题。

这篇关于vue 精选评论词云 集成echarts-wordcloud TF-IDF算法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1108415

相关文章

HTML5的input标签的`type`属性值详解和代码示例

《HTML5的input标签的`type`属性值详解和代码示例》HTML5的`input`标签提供了多种`type`属性值,用于创建不同类型的输入控件,满足用户输入的多样化需求,从文本输入、密码输入、... 目录一、引言二、文本类输入类型2.1 text2.2 password2.3 textarea(严格

SpringBoot返回文件让前端下载的几种方式

《SpringBoot返回文件让前端下载的几种方式》文章介绍了开发中文件下载的两种常见解决方案,并详细描述了通过后端进行下载的原理和步骤,包括一次性读取到内存和分块写入响应输出流两种方法,此外,还提供... 目录01 背景02 一次性读取到内存,通过响应输出流输出到前端02 将文件流通过循环写入到响应输出流

SpringBoot+Vue3整合SSE实现实时消息推送功能

《SpringBoot+Vue3整合SSE实现实时消息推送功能》在日常开发中,我们经常需要实现实时消息推送的功能,这篇文章将基于SpringBoot和Vue3来简单实现一个入门级的例子,下面小编就和大... 目录前言先大概介绍下SSE后端实现(SpringBoot)前端实现(vue3)1. 数据类型定义2.

Spring Boot 集成 mybatis核心机制

《SpringBoot集成mybatis核心机制》这篇文章给大家介绍SpringBoot集成mybatis核心机制,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值... 目录Spring Boot浅析1.依赖管理(Starter POMs)2.自动配置(AutoConfigu

SpringBoot集成iText快速生成PDF教程

《SpringBoot集成iText快速生成PDF教程》本文介绍了如何在SpringBoot项目中集成iText9.4.0生成PDF文档,包括新特性的介绍、环境准备、Service层实现、Contro... 目录SpringBoot集成iText 9.4.0生成PDF一、iText 9新特性与架构变革二、环

JAVA SpringBoot集成Jasypt进行加密、解密的详细过程

《JAVASpringBoot集成Jasypt进行加密、解密的详细过程》文章详细介绍了如何在SpringBoot项目中集成Jasypt进行加密和解密,包括Jasypt简介、如何添加依赖、配置加密密钥... 目录Java (SpringBoot) 集成 Jasypt 进行加密、解密 - 详细教程一、Jasyp

前端Visual Studio Code安装配置教程之下载、汉化、常用组件及基本操作

《前端VisualStudioCode安装配置教程之下载、汉化、常用组件及基本操作》VisualStudioCode是微软推出的一个强大的代码编辑器,功能强大,操作简单便捷,还有着良好的用户界面,... 目录一、Visual Studio Code下载二、汉化三、常用组件1、Auto Rename Tag2

springBoot (springCloud2025)集成redisCluster 集群的操作方法

《springBoot(springCloud2025)集成redisCluster集群的操作方法》文章介绍了如何使用SpringBoot集成RedisCluster集群,并详细说明了pom.xm... 目录pom.XMLapplication.yamlcluster配置类其他配置类连接池配置类Redis

vite搭建vue3项目的搭建步骤

《vite搭建vue3项目的搭建步骤》本文主要介绍了vite搭建vue3项目的搭建步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录1.确保Nodejs环境2.使用vite-cli工具3.进入项目安装依赖1.确保Nodejs环境

Nginx搭建前端本地预览环境的完整步骤教学

《Nginx搭建前端本地预览环境的完整步骤教学》这篇文章主要为大家详细介绍了Nginx搭建前端本地预览环境的完整步骤教学,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录项目目录结构核心配置文件:nginx.conf脚本化操作:nginx.shnpm 脚本集成总结:对前端的意义很多