1 数据预处理
数据预处理目的是得到形式一致的数据,使得后续按照统一的方式进行数据清洗。
- 每人汇总爬虫到的所有数据,按(评论,评分)的形式存入csv表格中;
- 去除重复评论,使用Numpy、Pandas等方式;
- 去除默认评论,以及长度过短的无效评论;
- 将所有评分划分为3个分类(1-2分为差评,3-4分为中评,5分为好评),使之成为三分类数据。
代码:
import numpy as np
import pandas as pd
df = pd.read_csv('2result.csv')
#2去除重复评论
df.drop_duplicates(inplace=True) #直接在数据集上进行删除
print(df.shape)
#3.去除默认评论,以及长度过短无效评论
df = df[~df['评论'].isin(['您没有填写内容,默认好评'])]
df = df[~df['评论'].isin(['此用户未填写评价内容'])]
for i in df['评论'].loc[:]:
if len(i) <= 5 or len(i) >512:
print(i)
df = df[~df['评论'].isin([i])]
#4对数据进行分类(1-2为差评,3-4为中评,5为好评)
df.loc[df['评分']==2,'评分'] = 1
df.loc[df['评分']==3,'评分'] = 2
df.loc[df['评分']==4,'评分'] = 2
df.loc[df['评分']==5,'评分'] = 3
#排序 按照列排序数据,默认升序排列
df = df.sort_values('评分')
#不保存和列索引,使用NULL来替代空字符串(行索引:header=False)
df.to_csv("3result.csv",index=False,na_rep="NULL")
运行前数据:
运行后数据格式:
2 数据清洗
做好统一形式的数据后,即可执行以下步骤进行数据清洗:
数据清洗步骤分如下几步,仅供参考:
- 数据去重,删除自己负责数据中的重复数据。(pandas中有去重的方法)
- 数据缺失值处理,统计数据(评论、标签)中是否存在缺失值,如果存在缺失值可以将一行数据删除。(pandas中有缺失值处理方法)
- 去除无用字符,包括英文字母和数字、表情符号和其他字符、冒号和空白。(可使用正则表达式)
- 统计数据长度,包括最小长度、最大长度、平均长度。后续使用预训练模型时,会有512个字符的长度限制。(pandas有列值统计方法,matplotlib可进行数据可视化)
- 统计好评、中评、差评的评论数量,查看数据是否均衡,如果数据不均衡,需要对部分数据再次进行爬取。(方法同上)
- 分词、去除停用词。停用词列表可以使用哈工大、百度等出品的停用词表,并将停用词表进行汇总,统一完成分词,并去除停用词。(停用词下载地址:stopWord = requests.get("https://raw.githubusercontent.com/goto456/stopwords/master/cn_stopwords.txt"))
- 将原始数据、分完词后的数据以及对应的标签写入CSV文件中,等待后续统一汇总。
- 初始清洗
代码:
import numpy as np
import pandas as pd
import re
df = pd.read_csv('4result.csv')
#1数据去重,删除自己负责数据中的重复数据
df.drop_duplicates(inplace=True)
#2.数据缺失值处理
df.dropna(inplace=True)
#3.去除无用字符,包括英文字母和数字、表情符号和其他字符、冒号和空白
for i in range(df.shape[0]):
df.iloc[i,0] = re.sub('[a-zA-Z0-9、,,!!@;+~!@¥……&*()————+=、|】}【{:;“‘《》·。?%:——()*.?: ]','',df.iloc[i,0] )
for i in df['评论'].loc[:]:
if len(i) <= 5 or len(i) >512:
df = df[~df['评论'].isin([i])]
#4.统计数据长度,包括最小长度、最大长度、平均长度。
df["length"] = df['评论'].apply(len)
df2 = df.length.value_counts() # 可以通过df.colname 来指定某个列,value_counts()在这里进行计数
print("数据长度 长度出现次数")
print(df2)
print('最大长度:',df.length.max())
print('最小长度',df.length.min())
#5.统计好评、中评、差评的评论数量,查看数据是否均衡,
df3 = df.评分.value_counts() # 可以通过df.colname 来指定某个列,value_counts()在这里进行计数
print("数据均衡性查看")
print(df3)
#df = df.drop('length',axix=1,inplace=True)
print('数据形态',df.shape)
#删除生成的length列
df.drop('length',axis = 1, inplace=True)##改变原始数据
#不保存和列索引,使用NULL来替代空字符串(行索引:header=False)
df.to_csv("5result.csv",index=False,na_rep="NULL")
初步清洗后结果:
根据查看数据均衡性,可以知道评分为2的数据稍微有点少,需要再进行爬取。
数据均衡性处理代码:
#5.统计好评、中评、差评的评论数量,查看数据是否均衡,
df3 = df.评分.value_counts() # 可以通过df.colname 来指定某个列,value_counts()在这里进行计数
print("数据均衡性查看,删除前:")
print(df3)
#删除不均衡的部分,删除行
df.reset_index(drop=True, inplace=True)
df = df.drop(labels=range(10000,11512), axis=0)
df = df.drop(labels=range(6000,6287), axis=0)
df = df.drop(labels=range(2,74), axis=0)
df3 = df.评分.value_counts() # 可以通过df.colname 来指定某个列,value_counts()在这里进行计数
print("数据均衡性查看,删除后:")
print(df3)
运行结果:
- 分词、去除停用词
停用词下载:由于当使用requests请求的时候次数过多如下:
解决方法,将txt下载下来,直接本地读取
先分词再去停用词的代码:
import jieba
import pandas as pd
# 创建停用词列表
def stopwordslist():
stopwords = [line.strip() for line in open('cn_stopwords.txt',encoding='UTF-8').readlines()]
return stopwords
# 对句子进行中文分词
def seg_depart(sentence):
# 对文档中的每一行进行中文分词
print("正在分词")
sentence_depart = jieba.cut(sentence.strip())
# 创建一个停用词列表
stopwords = stopwordslist()
# 输出结果为outstr
outstr = ''
# 去停用词
#print('分词后', sentence_depart)
for word in sentence_depart:
if word not in stopwords:
if word != '\t':
outstr += word
outstr += " "
return outstr
df = pd.read_csv('4result.csv')
df["分词"] = df['评论'].apply(len)
for i in range(df.shape[0]):
print(df.iloc[i,0])
inputs = df.iloc[i,0]
line_seg = seg_depart(inputs)
df.iloc[i, 2] = line_seg
print(i,'去除无用后',line_seg)
df.to_csv("5result.csv",index=False,na_rep="NULL")
运行结果: