数据挖掘01---文本分析(jieba分词和词云绘制)

一、定义:

文本挖掘:从大量文本数据中抽取出有价值的知识,并且利用这些知识重新组织信息的过程。

二、语料库(Corpus)

语料库是我们要分析的所有文档的集合。


import os
import os.path
 
filePaths = []  #定义一个数组变量
#再用OS.walk的方法传入目录
#文件所在的文件目录,命名为root
#root下的所有子目录,命名为dirs
#root下的所有文件,命名为files
for root, dirs, files in os.walk(
    "C:\\Python_DM\\2.1\\SogouC.mini\\Sample"
):
    #进行遍历,需要得到输入目录下的所有文件
    for name in files:  #为了拿到root目录下的所有文件,我们再次便利所有的文件(代码:for name in files:)把它追加到filePaths变量中去即可。
        filePaths.append(os.path.join(root, name)) 
"""
os.path.join,拼接文件路径的方法。如果没有name,则filepaths里面没有xx.txt文件,没有root则没有文件目录路径。
"""
 
import codecs  #编码转换
 
filePaths = [];
fileContents = [];
for root, dirs, files in os.walk(
    "C:\\Python_DM\\2.1\\SogouC.mini\\Sample"
):
    for name in files:
        filePath = os.path.join(root, name);
        filePaths.append(filePath);
        f = codecs.open(filePath, 'r', 'utf-8') #1.文件路径 2.打开方式 3.文件编码
        fileContent = f.read()
        f.close()
        fileContents.append(fileContent)
 
import pandas;
corpos = pandas.DataFrame({
    'filePath': filePaths, 
    'fileContent': fileContents
})

二、中文分词

2.1概念:

中文分词(Chinese Word Segmentation):将一个汉字序列切分成一个一个单独的词。

eg:我的家乡是广东省湛江市–>我/的/家乡/是/广东省/湛江市

停用词(Stop Words):
数据处理时,需要过滤掉某些字或词
√泛滥的词,如web、网站等。

√语气助词、副词、介词、连接词等,如 的,地,得;

2.2安装Jieba分词包:

最简单的方法是用CMD直接安装:输入pip install jieba,但是我的电脑上好像不行。

后来在这里:https://pypi.org/project/jieba/#files下载了jieba0.39解压缩后 放在Python36\Lib\site-packages里面,然后在用cmd,pip install jieba 就下载成功了,不知道是是什么原因。

然后我再anaconda 环境下也安装了jieba,先在Anaconda3\Lib这个目录下将jieba0.39的解压缩文件放在里面,然后在Anaconda propt下输入 pip install jieba,如下图:

2.3代码实战:

jieba最主要的方法是cut方法:

jieba.cut方法接受两个输入参数: 1) 第一个参数为需要分词的字符串 2)cut_all参数用来控制是否采用全模式

jieba.cut_for_search方法接受一个参数:需要分词的字符串,该方法适合用于搜索引擎构建倒排索引的分词,粒度比较细

注意:待分词的字符串可以是gbk字符串、utf-8字符串或者unicode

jieba.cut以及jieba.cut_for_search返回的结构都是一个可迭代的generator,可以使用for循环来获得分词后得到的每一个词语(unicode),也可以用list(jieba.cut(…))转化为list代码示例( 分词 )

import jieba;

for w in jieba.cut(“我爱Python”):
print(w)
输出结果为:


Python

for w in jieba.cut("""
工信处女干事
每月经过下属科室都要亲口交代
24口交换机等技术性器件的安装工作
“”"):
print(w)
工信处
女干事

每月
经过
下属
科室


亲口

交代

24

交换机

技术性
器件

安装

工作

分词功能用于专业的场景:

import jieba;
seg_list = jieba.cut(
“真武七截阵和天罡北斗阵哪个更厉害呢?”
)
for w in seg_list:
print(w)
会出现真武七截阵和天罡北斗阵被分成几个词。为了改善这个现象,我们用导入词库的方法。
import jieba;
jieba.add_word(‘真武七截阵’)#添加词库
jieba.add_word(‘天罡北斗阵’)
seg_list = jieba.cut(
“真武七截阵和天罡北斗阵哪个更厉害呢?”
)
for w in seg_list:
print(w)
但是,如果需要导入的单词很多,jieba.add_word()这样的添加词库的方法就不高效了。

我们可以用jieba.load_userdict(‘D:\PDM\2.2\金庸武功招式.txt’)方法一次性导入整个词库,txt文件中为每行一个特定的词。

2.3.1对大量文章进行分词

先搭建语料库:

分词后我们需要对信息处理,就是这个分词来源于哪个文章。

三、词频统计

3.1词频(Term Frequency):

某个词在该文档中出现的次数。

3.2利用Python进行词频统计

# -*- coding: utf-8 -*-
"""搭建语料库,及分词"""
import os
import os.path
import codecs
 
filePaths = []
fileContents = []
for root, dirs, files in os.walk(
    "C:\\Python_DM\\2.1\\SogouC.mini\\Sample"
):
    for name in files:
        filePath = os.path.join(root, name)
        filePaths.append(filePath);
        f = codecs.open(filePath, 'r', 'utf-8')
        fileContent = f.read()
        f.close()
        fileContents.append(fileContent)
 
import pandas;
corpos = pandas.DataFrame({
    'filePath': filePaths, 
    'fileContent': fileContents
});
 
import jieba
 
segments = []
filePaths = []
for index, row in corpos.iterrows():
    filePath = row['filePath']
    fileContent = row['fileContent']
    segs = jieba.cut(fileContent)
    for seg in segs:
        segments.append(seg)
        filePaths.append(filePath)
 
segmentDataFrame = pandas.DataFrame({
    'segment': segments, 
    'filePath': filePaths
})
 
"""filepath一直没变,对fileContents进行了分词,赋值如segment."""
 
 
import numpy
#进行词频统计        
segStat = segmentDataFrame.groupby( #调用groupby方法
            by="segment"
        )["segment"].agg({
            "计数":numpy.size
        }).reset_index().sort_values(#重新设置索引
            by=['计数'],
            ascending=False#倒序排序
        )
"""排在前面的为停用词"""
 
#移除停用词
stopwords = pandas.read_csv(
    "C:\\Python_DM\\2.3\\StopwordsCN.txt", 
    encoding='utf8', 
    index_col=False
)
 
#获得没有停用词的词频统计结果
fSegStat = segStat[
    ~segStat.segment.isin(stopwords.stopword)
]#'~'取反,不包含停用词的留下。
3.2.1移除停用词的另一种方法,加if判断

import os
import os.path
import codecs
 
filePaths = []
fileContents = []
for root, dirs, files in os.walk(
    "C:\\Python_DM\\2.1\\SogouC.mini\\Sample"
):
    for name in files:
        filePath = os.path.join(root, name)
        filePaths.append(filePath);
        f = codecs.open(filePath, 'r', 'utf-8')
        fileContent = f.read()
        f.close()
        fileContents.append(fileContent)
 
import pandas;
corpos = pandas.DataFrame({
    'filePath': filePaths, 
    'fileContent': fileContents
});
import jieba
 
segments = []
filePaths = []
for index, row in corpos.iterrows():
    filePath = row['filePath']
    fileContent = row['fileContent']
    segs = jieba.cut(fileContent)
    for seg in segs:#下面加一个判断,如果不在分词中就加入进分组,加一个条件:分词去除空格后的长度大于0
        if seg not in stopwords.stopword.values and len(seg.strip())>0:
            segments.append(seg)
            filePaths.append(filePath)
 
segmentDataFrame = pandas.DataFrame({
    'segment': segments, 
    'filePath': filePaths
});
 
segStat = segmentDataFrame.groupby(
            by="segment"
        )["segment"].agg({
            "计数":numpy.size
        }).reset_index().sort_values(
            by=["计数"],
            ascending=False
        );
代码中用到的一些常用方法:

分组统计:

DataFrame.groupby(
by=列名数组)[统计列明数组].agg({
‘统计项名称’:统计函数
})
判断一个数据框中的某一列的值是否包含一个数组中的任意一个值:
DataFrame.列名.isin(数组)
取反:(对布尔值)
df[~df.列名.isin(数组)]
四、词云绘制
词云(Word Cloud):是对文本中词频较高的分词,给与视觉上的突出,形成“关键词渲染”,从而国旅掉大量的文本信息,使浏览者一眼扫过就可以领略文本的主旨。

4.1安装词云工具包
这个地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/ ,可以搜到基本上所有的Python库,进去根据自己的系统和Python的版本进行下载即可。

在python下安装很方便,在anaconda下安装费了点劲,最终将词云的文件放在C:\Users\Administrator 这个目录下才安装成功。

-- coding: utf-8 --

import os;
import os.path;
import codecs;

filePaths = [];
fileContents = [];
for root, dirs, files in os.walk(
“C:\Python_DM\2.4\SogouC.mini\Sample\C000007”
):
for name in files:
filePath = os.path.join(root, name);
filePaths.append(filePath);
f = codecs.open(filePath, ‘r’, ‘utf-8’)
fileContent = f.read()
f.close()
fileContents.append(fileContent)

import pandas;
corpos = pandas.DataFrame({
‘filePath’: filePaths,
‘fileContent’: fileContents
});

import jieba

segments = []
filePaths = []
for index, row in corpos.iterrows():
filePath = row[‘filePath’]
fileContent = row[‘fileContent’]
segs = jieba.cut(fileContent)
for seg in segs:
segments.append(seg)
filePaths.append(filePath)

segmentDataFrame = pandas.DataFrame({
‘segment’: segments,
‘filePath’: filePaths
});

import numpy;
#进行词频统计
segStat = segmentDataFrame.groupby(
by=“segment”
)[“segment”].agg({
“计数”:numpy.size
}).reset_index().sort_values(
by=[“计数”],
ascending=False
);

#移除停用词
stopwords = pandas.read_csv(
“C:\Python_DM\2.4\StopwordsCN.txt”,
encoding=‘utf8’,
index_col=False
)

fSegStat = segStat[
~segStat.segment.isin(stopwords.stopword)
]

#绘画词云
#http://www.lfd.uci.edu/~gohlke/pythonlibs/
from wordcloud import WordCloud
import matplotlib.pyplot as plt

#传入字体文件的路径,还有背景颜色
#微软雅黑的字体,黑色背景
wordcloud = WordCloud(
font_path=‘C:\Python_DM\2.4\simhei.ttf’,
background_color=“black”
)

#把分词设置成数据框的索引,再调用to_dict()的方法,获得一个字典的数据结构了。
words = fSegStat.set_index(‘segment’).to_dict()

wordcloud.fit_words(words[‘计数’])

plt.imshow(wordcloud)

#plt.close()
五、美化词云(词云放入某图片形象中)
六、关键词提取
import os
import codecs
import pandas
import jieba
import jieba.analyse #关键字提取方法

#定义好存储的列数组,抽取5个关键字
filePaths = []
contents = []
tag1s = []
tag2s = []
tag3s = []
tag4s = []
tag5s = []

for root, dirs, files in os.walk(
“C:\Python_DM\2.6\SogouC.mini\Sample\”
):
for name in files:
filePath = root + ‘\’ + name;
f = codecs.open(filePath, ‘r’, ‘utf-8’)
content = f.read().strip()
f.close()

    #将文件内容(content)传递给extract_tags方法
    #把管家你在tags添加到对应的列中
    tags = jieba.analyse.extract_tags(content, topK=5)
    filePaths.append(filePath)
    contents.append(content)
    tag1s.append(tags[0])
    tag2s.append(tags[1])
    tag3s.append(tags[2])
    tag4s.append(tags[3])
    tag5s.append(tags[4])

tagDF = pandas.DataFrame({
‘filePath’: filePaths,
‘content’: contents,
‘tag1’: tag1s,
‘tag2’: tag2s,
‘tag3’: tag3s,
‘tag4’: tag4s,
‘tag5’: tag5s
})
结果如下:

七、关键词提取实现

词频(Term Frequency):

指的是某一个给定的词在该文档中出现的次数。

计算公式: TF = 该次在文档中出现的次数

逆文档频率(Inverse Document Frequency)

IDF就是每个词的权重,它的大小与一个词的常见程度成反比。

计算公式:IDF = log(文档总数/(包含该词的文档数 - 1))

TF-IDF(Term Frequency-Inverse Document Frequency)

权衡某个分词是否关键词的指标,该值越大,是关键词的可能性就越大。

计算公式:TF - IDF = TF * IDF

猜你喜欢

转载自blog.csdn.net/ZZQHELLO2018/article/details/85060767