文本挖掘(超详细)
工具:八爪鱼采集器 + Python + JavaScript朋友们好,文本挖掘这篇文章写了也有一段时间了,承蒙朋友们的厚爱,作者后面有做过一个升级版的文本挖掘,但苦于没有时间一直没有更新,现在在抽时间把后面写的这个也发布出来,两篇文章的步骤可能并不一致,但也许能给大家的学习带来帮助。另外,两篇文章的部分资源都是需要些许积分的,仅仅是因为作者也需要积分学习哈,希望大家不要介意呐~
文本挖掘(爬虫 - 预处理 - 特征词提取 - 特征词聚类 - 特征词情感)
例如:数据获取 - 数据清洗 - 中文分词 - 去除停用词 - 词频统计 - 词云图 - 情感分析
数据获取
工具:八爪鱼采集器链接:下载
使用:
1、 下载压缩包并解压
2、 点击 .exe 文件安装
3、 使用模板采集数据/自定义配置采集数据
示例:
1、 选择模板




数据清洗
简单的数据清洗:把评论内容复制放到一个 Word 文档中,通过文本的 查找与替换 功能去除京东的评论模板文本。Before:


中文分词
工具:Python + VS Code 软件VS Code 配置 Python 环境:自行搜索
代码:
import jieba
import jieba.analyse
# 待分词的文本路径
sourceTxt = 'comment_1.txt'
# 分好词后的文本路径
targetTxt = 'comment_1_fenci.txt'
# 对文本进行操作
with open(sourceTxt, 'r', encoding = 'utf-8') as sourceFile, open(targetTxt, 'a+', encoding = 'utf-8') as targetFile:
for line in sourceFile:
seg = jieba.cut(line.strip(), cut_all = False)
# 分好词之后之间用空格隔断
output = ' '.join(seg)
targetFile.write(output)
targetFile.write('\n')
prinf('写入成功!')
# 提取关键词
with open(targetTxt, 'r', encoding = 'utf-8') as file:
text = file.readlines()
"""
几个参数解释:
* text : 待提取的字符串类型文本
* topK : 返回TF-IDF权重最大的关键词的个数,默认为20个
* withWeight : 是否返回关键词的权重值,默认为False
* allowPOS : 包含指定词性的词,默认为空
"""
keywords = jieba.analyse.extract_tags(str(text), topK = 10, withWeight=True, allowPOS=())
print(keywords)
print('提取完毕!')
注意:1、 导入 jieba 包:pip install jieba(命令行操作,需要转到当前目录)
After:

去除停用词
工具:Python + VS Code 软件代码:
import jieba
# jieba.load_userdict('userdict.txt')
# 创建停用词list
def stopwordslist(filepath):
stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()]
return stopwords
def seg_sentence(sentence):
sentence_seged = jieba.cut(sentence.strip())
stopwords = stopwordslist('cn_stopwords.txt') # 这里加载停用词的路径
outstr = ''
for word in sentence_seged:
if word not in stopwords:
if word != '\t':
outstr += word
outstr += " "
return outstr
inputs = open('comment_1.txt', 'r', encoding='utf-8')
outputs = open('comment_1_fenci_qutingyongci.txt', 'w',encoding='utf-8')
for line in inputs:
line_seg = seg_sentence(line) # 这里的返回值是字符串
outputs.write(line_seg + '\n')
outputs.close()
inputs.close()
After:
词频统计
工具:Python + VS Code 软件代码:
import jieba
import re
#打开要处理的文章
reader = open("comment_1_fenci_qutingyongci.txt",'r',encoding='utf8')
strs =reader.read()
result = open("comment_1_fenci_qutingyongci_cipin.txt","w")
# 分词,去重,列表
word_list = jieba.cut(strs,cut_all=True)
# 正则表达式去除数字,符号,单个字
new_words = []
for i in word_list:
m = re.search("\d+",i)
n = re.search("\W+",i)
if not m and not n and len(i)>1:
new_words.append(i)
# 统计词频
word_count = {} # 创建字典
for i in set(new_words): # 用set去除list中的重复项
word_count[i] = new_words.count(i)
# 格式整理
list_count = sorted(word_count.items(),key=lambda co:co[1],reverse=True)
# 打印结果
for i in range(300):
print(list_count[i],file=result)
#关闭文件
reader.close()
result.close()
After: 
词云图
工具:JavaScript + Sublime Text 软件链接:下载 Sublime Text
代码:下载完整代码
词频处理:
通过 Word 的 文本与替换 和 Excel 的 分列 可得

图片转码:转码
After:

情感分析
工具:Python + VS Code 软件代码:
#加载情感分析模块
from snownlp import SnowNLP
#from snownlp import sentiment
import pandas as pd
import matplotlib.pyplot as plt
#导入样例数据
aa ='comments.xlsx'
#读取文本数据
df=pd.read_excel(aa)
#提取所有数据
df1=df.iloc[:,3]
print('将提取的数据打印出来:\n',df1)
#遍历每条评论进行预测
values=[SnowNLP(i).sentiments for i in df1]
#输出积极的概率,大于0.5积极的,小于0.5消极的
#myval保存预测值
myval=[]
good=0
bad=0
for i in values:
if (i>=0.5):
myval.append("正面")
good=good+1
else:
myval.append("负面")
bad=bad+1
df['预测值']=values
df['评价类别']=myval
#将结果输出到Excel
df.to_excel('comments_qinggan.xlsx')
rate=good/(good+bad)
print('好评率','%.f%%' % (rate * 100)) #格式化为百分比
#作图
y=values
plt.rc('font', family='SimHei', size=10)
plt.plot(y, marker='o', mec='r', mfc='w',label=u'评价分值')
plt.xlabel('用户')
plt.ylabel('评价分值')
# 让图例生效
plt.legend()
#添加标题
plt.title('IQOO5 评论情感分析',family='SimHei',size=14,color='blue')
plt.show()
注意:1、 导入 SnowNLP 包:下载 SnowNLP 的 Github 源码并解压,在解压目录,通过下面命令安装
python setup.py install
2、导入 pandas 包:链接 下载之后,可以将文件改为 zip 格式的,然后解压,将解压之后的文件夹中的两个文件放到 Python 的安装目录 –> Lib –> site-packages

