解析旅游者心声:用PySpark和SnowNLP揭秘景区评论的情感秘密

简介:

在本篇博客中,我们将探讨如何利用PySpark和SnowNLP这两个强大的工具来分析大规模的旅游评论数据。通过结合携程和去哪儿的数据作为示例,我们将探索如何从海量的评论中提取有价值的情感信息和洞察。PySpark作为一种分布式计算框架,能够处理大规模的数据集,为我们提供了处理大数据的能力。而SnowNLP作为一种自然语言处理工具,能够帮助我们对中文文本进行情感分析,从而揭示出评论中隐藏的情感倾向和情感趋势。通过本文的学习,读者将不仅了解情感分析的基本原理和技术,还能掌握如何利用这些技术来解读和分析旅游评论数据,为旅游业的改进和优化提供实际的指导和建议。

开发环境

Python,HDFS,spark,hive。

链接hive

Python 复制代码
# Author: 冷月半明
# Date: 2023/12/7
# Description: This script does XYZ.
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, StringType, IntegerType


# 创建SparkSession并连接到远程Spark服务器
spark = SparkSession.builder.appName("RemoteSparkConnection").master("yarn").config("spark.pyspark.python", "/opt/apps/anaconda3/envs/myspark/bin/python").getOrCreate()


print("链接成功")
# 使用spark.sql()从Hive表中读取数据
df = spark.sql("SHOW DATABASES;")

# 显示数据
df.show()
# 关闭SparkSession
spark.stop()

此时因为没指定源数据库位置信息,因此只有默认库。 网上解决方式有两种,其一在使用pyspark是指定元数据位置,其二在spark设置里粘入hive-site.xml,在此使用第一种方式。

当指定元数据存储位置后再次查询,就能正常显示。

计算去哪网的情感得分

Python 复制代码
def qvna():
    print("链接成功")
    df = spark.sql("SELECT * FROM cjw_data.qvna;")
    print(type(df))
   
    # 定义一个新的 UDF,用于计算每一行的平均情感值
    def calculate_average_sentiment(commentlist):
        try:
            jsonstr = str(commentlist)
            python_obj = json.loads(jsonstr, strict=False)
        except:
            return None

        contentcores = []
        for item in python_obj:
            for i in item:
                if (i["content"] != "用户未点评,系统默认好评。"):
                    contentcores.append(SentimentAanalysis(i["content"]))
        if len(contentcores) > 0:
            average = sum(contentcores) / len(contentcores)
        else:
            average = None  # 如果数组为空,返回 None
        return average

    calculate_average_sentiment_udf = udf(calculate_average_sentiment, StringType())
    # 使用 withColumn 方法添加新的字段
    df = df.withColumn("average_sentiment", calculate_average_sentiment_udf(df["commentlist"]))
    newdf = df.select("id", "title", "price", "average_sentiment")
    newdf.write.mode("overwrite").saveAsTable("cjw_data.qvnasentiment")
    print(newdf)
    print(newdf.count())
    newdf.show(20)

首先,我们通过 PySpark 的 spark.sql() 方法连接到数据源,并获取评论数据,然后将其存储在 DataFrame 中。接着,我们定义了一个名为 calculate_average_sentiment 的函数,用于计算每条评论的平均情感值。在这个函数中,我们首先将评论数据转换为 JSON 字符串,并遍历每个评论内容,提取非默认好评的内容,然后使用 SentimentAanalysis 函数对评论内容进行情感分析,计算出情感分数的平均值,并将其作为新的字段添加到 DataFrame 中。

然后,我们使用 withColumn 方法将计算得到的平均情感值添加到 DataFrame 中,并选择需要保留的字段。最后,我们将结果 DataFrame 写入到新的表 cjw_data.qvnasentiment 中,并输出 DataFrame 的统计信息和前20行数据。

计算携程网的情感得分

Python 复制代码
def xiecheng():
    print("链接成功")

    df = spark.sql("SELECT * FROM cjw_data.xiecheng_jsoncleaned;")


    def calculate_average_sentiment(commentlist):
        try:
            jsonstr = str(commentlist)
            python_obj = json.loads(jsonstr, strict=False)
            contentcores = []
            for item in python_obj:
                contentcores.append(SentimentAanalysis(item["msg"]))
        except:
            return None

        if len(contentcores) > 0:
            average = sum(contentcores) / len(contentcores)
        else:
            average = None  # 如果数组为空,返回 None
        return average

    calculate_average_sentiment_udf = udf(calculate_average_sentiment, StringType())
    # 使用 withColumn 方法添加新的字段
    df = df.withColumn("average_sentiment", calculate_average_sentiment_udf(df["commentlist"]))
    newdf = df.select("id", "title",  "average_sentiment")
    # newdf.write.mode("overwrite").saveAsTable("cjw_data.xiechengsentiment")
    # 将DataFrame保存到临时表中

    newdf.show(20)
    # newdf.write.mode("overwrite").saveAsTable("cjw_data.temp_table")
    newdf.createOrReplaceTempView("tmp1")
    spark.sql("use cjw_data")
    spark.sql("create table xiechengsentiment as  select * from tmp1")

详细解释和分析:

  1. 函数 xiecheng() 首先打印出成功连接的消息,然后从数据源 cjw_data.xiecheng_jsoncleaned 中获取携程网站的评论数据,并将其存储在 DataFrame df 中。
  2. 定义了一个名为 calculate_average_sentiment 的函数,用于计算评论的平均情感值。该函数首先将评论数据转换为 JSON 格式,然后遍历评论中的每条信息,并使用 SentimentAanalysis 函数对评论内容进行情感分析,计算出情感分数的平均值,并将其返回。
  3. 然后,使用 udf 方法将 calculate_average_sentiment 函数注册为UDF(用户定义的函数),以便在 Spark SQL 中使用。
  4. 使用 withColumn 方法将计算得到的平均情感值添加为新的字段 average_sentiment 到 DataFrame df 中。
  5. 选择需要保留的字段,并将结果 DataFrame 写入临时表 tmp1 中。
  6. 最后,将临时表的数据存储到新的表 cjw_data.xiechengsentiment 中,完成了情感分析结果的存储过程。

合并计算两个表的信息。

Python 复制代码
def calculate():
    print("链接成功")
#     sqlstr="" \
#            "SELECT "\
# " COALESCE(t1.id, t2.id) as id,"\
# "    COALESCE(t1.title, t2.title) as title,"\
# " CASE " \
# "        WHEN t1.average_sentiment IS NOT NULL AND t2.average_sentiment IS NOT NULL THEN " \
# "            (t1.average_sentiment + t2.average_sentiment) / 2 " \
# "        ELSE" \
# "            COALESCE(t1.average_sentiment, t2.average_sentiment) " \
# "    END as average_sentiment " \
# "FROM "\
#   " cjw_data.qvnasentiment t1  "\
# "JOIN "\
# "   cjw_data.xiechengsentiment  t2  "\
# "ON "\
# "    t1.id = t2.id;"\


    sqlstr = ("SELECT COALESCE(t1.id, t2.id) AS id,"
              " COALESCE(t1.title, t2.title) AS title, "
              "CASE WHEN t1.id IS NOT NULL AND t2.id IS NOT NULL "
              "THEN (t1.average_sentiment + t2.average_sentiment) / 2 "
              "WHEN t1.id IS NOT NULL"
              " THEN t1.average_sentiment "
              "ELSE t2.average_sentiment END AS average_sentiment"
              " FROM cjw_data.qvnasentiment t1 "
              "FULL OUTER JOIN cjw_data.xiechengsentiment t2 "
              "ON t1.id = t2.id;")

    # sqlstr = ("SELECT * FROM  cjw_data.qvnasentiment LIMIT 5;")
    # df = spark.sql(sqlstr).limit(5)
    # df.show(5)
    # print("共有",df.count(), "行数据")
    df1 = spark.table("cjw_data.qvnasentiment")
    df2 = spark.table("cjw_data.xiechengsentiment")
    df1 = df1.drop("price")
    result = df1.join(df2, "id", "left_outer")
    result.show(20)
    # 筛选出在表一中有对应行而在表二中没有的记录
    missing_records = result.filter(result["xiechengsentiment.id"].isNull())
    missing_records = missing_records.select("qvnasentiment.id","qvnasentiment.title","qvnasentiment.average_sentiment")
    missing_records = missing_records.filter(result["qvnasentiment.average_sentiment"].isNotNull() & result["qvnasentiment.id"].isNotNull())
    print("去哪有携程没有共有",missing_records.count(), "行数据")
    missing_records.show(20)

    result = df1.join(df2, on="id", how="right_outer")
    missing_records2 = result.filter(result["qvnasentiment.id"].isNull())
    missing_records2 = missing_records2.select("xiechengsentiment.id","xiechengsentiment.title","xiechengsentiment.average_sentiment")
    missing_records2 = missing_records2.filter(result["xiechengsentiment.average_sentiment"].isNotNull() & result["xiechengsentiment.id"].isNotNull())
    print("携程有去哪没有",missing_records2.count(), "行数据")
    missing_records2.show(20)

    result = df1.join(df2, on="id", how="inner")
    result = result.withColumn('xiechengsentiment.average_sentiment', col('xiechengsentiment.average_sentiment').cast('float'))
    result = result.withColumn('qvnasentiment.average_sentiment', col('qvnasentiment.average_sentiment').cast('float'))
    def calculate_average_sentiment(xiecheng,qvna):
        # 将字符串转换为浮点数
        if xiecheng is not None:
            xiecheng = float(xiecheng)

        if qvna is not None:
            qvna = float(qvna)

        try:
            if (qvna is None) and (xiecheng is None):
                return None
            elif xiecheng is None:
                return qvna
            elif qvna is None:
                return xiecheng
            else:
                return (xiecheng + qvna) /2
        except:
            return None
    calculate_average_sentiment_udf = udf(calculate_average_sentiment, StringType())
    # 使用 withColumn 方法添加新的字段
    result = result.withColumn("average_sentiment3", calculate_average_sentiment_udf(result["xiechengsentiment.average_sentiment"],result["qvnasentiment.average_sentiment"]))
    # 过滤掉average_sentiment3为null的行
    missing_records3 = result.filter(result["average_sentiment3"].isNotNull())
    missing_records3 = missing_records3.select("id", "xiechengsentiment.title","average_sentiment3")
    print("两者都有", missing_records3.count(), "行数据")
    missing_records3.show(20)

    final_df = missing_records.union(missing_records2).union(missing_records3)
    final_df = final_df.dropDuplicates(["id"])
    print("共有", final_df.count(), "行数据")
    final_df.show(20)
    # final_df.write.mode("overwrite").saveAsTable("cjw_data.toursentiment")
    print("写入成功")

本想使用spark SQL去执行合并计算,但奈何自己水平太菜,写的SQL总是不能达到目的,无奈使用dataframeAPI去完成需求。

但发现只有1693行数据,问题出在

t1.id = t2.id

重新修改逻辑

假如xiecheng表为表一,qvna表为表二

1.若表一中有一行id1,表二中没有相应行id2=id1,取表一id1哪行。

2.若表二中有一行id2,表一中没有相应行id1=id2,取表二id2哪行。

3.若表一中有一行id1,表二中存在id2=id1,那一行的average_sentiment字段和再除2

先使用join左连接筛选出加上filter(result["xiechengsentiment.id"].isNull())筛选出一个df1

然后使用join右链接加上filter(result["qvnasentiment.id"].isNull())筛选出一个df2

最后使用join内连接加上udf函数计算均值晒选出df3

最后使用union将df1,df2,df3合并

最终函数逻辑如下

  1. 从两个数据表 cjw_data.qvnasentimentcjw_data.xiechengsentiment 中获取数据。
  2. 对这两个数据表进行左连接、右连接和内连接,并根据id字段进行连接操作。
  3. 根据连接操作的结果,筛选出在一个表中有对应行而在另一个表中没有的记录,并进行打印展示。
  4. 定义了一个计算平均情感值的函数 calculate_average_sentiment(),并注册为UDF(用户定义的函数)。
  5. 使用 withColumn 方法将计算得到的平均情感值添加为新的字段到DataFrame中。
  6. 过滤掉其中平均情感值为空的行,并进行打印展示。
  7. 将三个结果DataFrame合并,并去除重复记录,最后进行展示和持久化存储至hive。
  8. 最后,打印出写入成功的消息。

可能遇到的问题

一旦存储数据到hive就报错

设置try后写入成功,但进入hive查询出错

后来发现是以下原因

增加写入配置

Python 复制代码
.config("spark.sql.parquet.writeLegacyFormat", "true") \

成功写入。

spark不能覆盖正在读取的表

假如在本次链接中使用spark SQL读取了表1的数据,那么就不能再覆盖表1了。

解决方式

python 复制代码
# 原代码
newdf.write.mode("overwrite").saveAsTable("cjw_data.xiechengsentiment")
#新代码, 将DataFrame保存到临时表中
newdf.write.mode("overwrite").saveAsTable("temp_table")

# 使用临时表覆盖原始表
spark.sql("DROP TABLE IF EXISTS cjw_data.xiechengsentiment")
spark.sql("ALTER TABLE temp_table RENAME TO xiechengsentiment")

总结

在本文中,我们使用了PySpark和SnowNLP工具对大规模旅游评论数据进行了情感分析。通过连接到Hive数据库,并利用PySpark从中提取数据,我们能够处理大规模的数据集。SnowNLP作为自然语言处理工具,帮助我们进行情感分析,从而揭示了评论中的情感倾向和趋势。

我们通过计算每条评论的平均情感值,并将结果存储到新的数据表中。通过合并不同数据表的信息,我们得到了综合的情感分析结果,并进行了展示和持久化存储。

如果本篇博客对您有帮助,请点赞支持。

相关推荐
Kenneth風车23 分钟前
【机器学习(九)】分类和回归任务-多层感知机 (MLP) -Sentosa_DSML社区版
人工智能·算法·低代码·机器学习·分类·数据分析·回归
Fan35 分钟前
Elasticsearch 下载安装及使用总结
大数据·elasticsearch·jenkins
need help1 小时前
CDA Level 1 业务数据分析
数据挖掘·数据分析
m0_713344852 小时前
新能源汽车数据大全(产销数据\充电桩\专利等)
大数据·人工智能·新能源汽车
goTsHgo2 小时前
从底层原理上解释 ClickHouse 的索引
大数据·clickhouse
凑齐六个字吧2 小时前
单样本Cellchat(V2)细胞通讯分析学习和整理
数据分析
Yz98762 小时前
Hadoop-MapReduce的 原理 | 块和片 | Shuffle 过程 | Combiner
大数据·数据库·数据仓库·hadoop·mapreduce·big data
新榜有数2 小时前
品牌建设是什么?怎么做好品牌建设?
大数据·矩阵·数据分析·新媒体运营·流量运营·媒体·内容运营
好记性+烂笔头3 小时前
Flink提交任务
大数据·flink
goTsHgo3 小时前
Flink 中 Checkpoint 的底层原理和机制
大数据·flink