欢迎光临散文网 会员登陆 & 注册

记录一次特征词分析

2023-03-05 16:24 作者:暗冥_紫  | 我要投稿

先介绍一些语句

%matplotlib inline 可以在Ipython编译器里直接使用,功能是可以内嵌绘图,并且可以省略掉plt.show()这一步,是一个魔法函数。

data['comment_star'].value_counts()  # 将data的对应name的列的元素排序统计。

data.log[3]  # 提取DataFrame对应index的那一行装换成Series并把列的name转为index。

data.log[3, 'x']  # 在上面的基础上提取index为‘x’的元素(注意是从Series提取)

Series.index() Series.values() 分别提取Series的值与索引 输出<class 'numpy.ndarray'>

Series类的str属性:针对字符串进行处理

findall() 查找所有符合正则表达式的字符并以数组形式返回,get() 获取指定位置的字符串


import pandas as pd

from pandas import Series,DataFrame

from matplotlib import pyplot as plt

import seaborn as sns

from wordcloud import WordCloud, STOPWORDS

from PIL import Image #导入模块PIL(Python Imaging Library)图像处理库

import numpy as np #导入模块numpy,多维数组

import matplotlib

%matplotlib inline


data = pd.read_csv('input.csv')

data

data.loc[data['comment_star'] == 'sml-str1','comment_star'] = 'sml-str10'

# 将data"comment_star"列的数据'sml-str1'转为'sml-str10'


data['stars'] = data['comment_star'].str.findall(r'\d+').str.get(0)  # 提取数字 

data['stars']

data['stars'] = data['stars'].astype('float')/10  # 将分数缩小10倍

sns.countplot(data=data, x='stars')

sns.countplot(data=data, x='stars')
data['shopID'].value_counts()
sns.boxplot(data=data, x='shopID', y='stars')

data.comment_time = pd.to_datetime(data.comment_time.str.findall(r'\d{4}-\d{2}-\d{2} .+').str.get(0))  # 切分时间方便之后分析

data['year'] = data.comment_time.dt.year

data['month'] = data.comment_time.dt.month

data['weekday'] = data.comment_time.dt.weekday

data['hour'] = data.comment_time.dt.hour

data
data['hour'].value_counts()

df=data.groupby(['hour', 'weekday']).count()  # 以指定的这两个name进行分组

df['cus_id'].unstack()

fig1, ax1=plt.subplots(figsize=(14,4))

print(fig1, type(ax1))

df['cus_id'].unstack().plot(ax=ax1, style='-.')

plt.show()

data['comment_len'] = data['cus_comment'].str.len()  # 查看评论长度

fig2, ax2=plt.subplots()

sns.boxplot(x='stars',y='comment_len',data=data,ax=ax2)

ax2.set_ylim(0,600)  # 设置最大y值


data['cus_comment1'] = data['cus_comment'].str.replace(r'[^\u4e00-\u9fa5]','').str.replace('收起评论','')  # 使用Unicode 消去非中文字符


#中文分词

import jieba


infile = open("stopwords.txt",encoding='utf-8')

stopwords_lst = infile.readlines()

STOPWORDS = [x.strip() for x in stopwords_lst]

stopwords = set(STOPWORDS)  # 设置停用词

data['cus_comment1'].fillna(' ',inplace=True)  # 将None数据转为空格

data['cus_comment1'] = data['cus_comment1'].apply(lambda x:' '.join(jieba.cut(x)))  # 分词


data[['cus_id','stars','cus_comment1']].to_csv(path_or_buf='data-out.csv')  # 保存为csv



matplotlib.rcParams['font.sans-serif'] = ['KaiTi']#作图的中文

matplotlib.rcParams['font.serif'] = ['KaiTi']#作图的中文


def ciyun(shop_ID='all'):

    texts = data['cus_comment1']

    if shop_ID == 'all':

        text = ' '.join(texts)

    else:

        text = ' '.join(texts[data['shopID']==shop_ID])

    wc = WordCloud(font_path="simsun.ttc", background_color='white', max_words=100,         stopwords=stopwords, max_font_size=80, random_state=42, margin=3)  # 配置词云参数

    wc.generate(text)  # 生成词云

    plt.imshow(wc,interpolation="bilinear")  # 作图

    plt.axis("off")  # 不显示坐标轴

        

ciyun(521698)


总结:

主要使用pandas、matplolib、seaborn

本次程序实现了分析总打分数、商品打分数、消费时间,将分词保存为csv,词云展示评价

记录一次特征词分析的评论 (共 条)

分享到微博请遵守国家法律