1 数据准备
数据样例如下, 数据总量为7.7万+:
本节通过一个实战的例子来展示文本分析的最简单流程。首先设定因变量为原始数据中的"评分"。自变量是"评价内容",这里根据评价内容提取TF-IDF特征。之后,通过评价内容的特征建模预测下整体评分。
import jieba #导入分词模块
import pandas as pd # 导入Pandas模块
# 1. 导入数据
comments_df = pd.read_excel("https://github.com/xiangyuchang/xiangyuchang.github.io/blob/master/BearData/comment_nm.xlsx?raw=true") #读入数据
print('数据的维度是:', comments_df.shape)
comments_df.head() #查看数据的前5行
# 2. 清洗数据, 删除空的数据
def clean_sents(txt):
txt = str(txt) if txt is not None else ""
if len(txt) == 0:
return None
else:
return txt
comments_df2["评价内容"] = comments_df2["评价内容"].apply(clean_sents)
comments_df2 = comments_df2[comments_df2["评价内容"] != "nan"]
len(comments_df2)
# 运行结果
# 58117
以上只是最基本的数据清洗(删除缺失值), 这里不再赘述。过滤后, 样本量为5.8W+条, 减少2.2万+。
2 分词
文本分析的第一步是分词。常用中文包是jieba: https://github.com/fxsjy/jieba.
再次声明, 本书为平滑学习曲线, 仅对最重要的函数进行调用和说明, 在实际中不够用时请自行翻阅对应的官方文档。成熟的开源库基本都有完善的文档, 即学即用即可。
# 引入停用词文本,请在如下网址下载:https://github.com/zhiyiZeng/cluebearpython/blob/master/chapter8/data/stopwords.txt
stopwords_file = "stopwords.txt"
with open(os.path.join(path, stopwords_file), "r", encoding="utf8") as f:
stopwords_list = [word.strip() for word in f