数据挖掘-文本分析

含义:文本分析是指对文本的表示及其特征项的选取;文本分析是文本挖掘、信息检索的一个基本问题,它把从文本中抽取出的特征词进行量化来表示文本信息。

分析过程:

1.搭建语料库(即要分析文章的集合)。
知识点:os模块

import os;
import os.path;
import codecs;
#数组变量
filePaths=[];
fileContents = [];
#文件目录,文件夹下的子目录,文件
for root,dirs,files in os.walk(   
    #文件路径,注意Windows下应是 ‘\\’
    "C:\\Users\\Desktop\\Python\\DM\\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
        })
 
#导入文件的时候, 设置 utf-8 文件编码,文件中存在异常词,可能会报错
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbf in position 0: invalid start byte
解决方法:
将  f=codecs.open(filePath,'r','utf-8') 替换成
f=codecs.open(filePath,'r','gb18030',errors='ignore')
即可实现文件的正常读取。

2.中文分词—“结巴分词”
知识点:jieba
安装:pip install jieba

import jieba
segments = []    #分词
filePaths = []     #文件路径
#遍历数据,完成分词
for index, row in corpos.iterrows():
    filePath = row['filePath']
    fileContent = row['fileContent']
#分词 jieba.cut(需要分词的文件)返回数组
    segs = jieba.cut(fileContent)  
    for seg in segs:
        segments.append(seg)
        filePaths.append(filePath)
segmentDataFrame = pandas.DataFrame({
    'segment': segments, 
    'filePath': filePaths
});

注:如果分词结果,不符合预期,可采用以下方法。

  1. 可增加自定义分词:jieba.add_word(word) #word为需要增加的分词
  2. 导入自定义字典:jieba.load_userdict(filePath)#filePath文件路径

3.统计词频

import numpy;
#进行词频统计        
segStat = segmentDataFrame.groupby(
            by="segment"
        )["segment"].agg({
            "计数":numpy.size
        })
text=segStat.reset_index(
         drop=False
        );

#移除停用词
#第一种方法,最后去掉停用词。
stopwords = pandas.read_csv(
    "C:\\Users\\lls\\Desktop\\Python\\DM\\StopwordsCN.txt", 
    encoding='utf8', 
    index_col=False
)

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

#第二种方法,分词过程中过滤掉停用词
import jieba
segments = []
filePaths = []
for index, row in corpos.iterrows():
    filePath = row['filePath']
    fileContent = row['fileContent']
    segs = jieba.cut(fileContent)
    for seg in segs:
        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
});

segStattext = segmentDataFrame.groupby(
            by="segment"
        )["segment"].agg({
            "计数":numpy.size
        })

停用词:是指在信息检索中,为节省存储空间和提高搜索效率,在处理自然语言数据(或文本)之前或之后会自动过滤掉某些字或词,这些字或词即被称为Stop Words(停用词)。 这些停用词都是人工输入、非自动化生成的,生成后的停用词会形成一个停用词表。 但是,并没有一个明确的停用词表能够适用于所有的工具。

分组统计
DataFrame.groupby(by=列名数组)[统计列名数组].agg({‘统计项名称’:统计函数})

列表包含:DataFrame.列名.isin(数组)

取反:df[~df.列名.isin(数组)]


数据呈现:

词云绘制

1.下载Wordcloud文件  地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/ 
   win + R   调出命令窗口 pip install wordcloud-1.2.1-cp35-cp35m-win_amd64.whl
   
2.绘制词汇云
from wordcloud import WordCloud
import matplotlib.pyplot as plt
wordcloud = WordCloud(
    font_path="C:\\Users\\lls\\Desktop\\Python\\DM\\2.4\\2.4\\simhei.ttf", 
    background_color="black"
)
words = text.set_index('segment').to_dict()
wordcloud.fit_words(words['计数'])
plt.imshow(wordcloud)

在这里插入图片描述
知识点总结:
生成wordcloud对象
wordcloud=WordCloud( font_path=‘simhei.ttf’, #中文字体
background_color=“black” #背景颜色)
绘制:wordcloudImg = wordclound.fit_words(dict)

词云图美化

from scipy.misc import imread
import matplotlib.pyplot as plt
from wordcloud import WordCloud,ImageColorGenerator
bimg = imread("C:\\Users\\lls\\Desktop\\aaa.png")   #导入图片
wordcloud = WordCloud(
    background_color="white", 
    mask=bimg,     #图片赋值给变量
    font_path="C:\\Users\\lls\\Desktop\\Python\\simhei.ttf"
)
wordcloud = wordcloud.fit_words(words['计数'])
#设置词云图的大小
plt.figure(
        num=None,
        figsize=(8,6),dpi=80,
        facecolor='w',edgecolor='k'
        )     
bimgColors = ImageColorGenerator(bimg)
plt.axis("off")
plt.imshow(wordcloud.recolor(color_func=bimgColors))
plt.show()

知识点:
读取图片背景:bimg=imread(imgFilePath)
获取图片颜色:bimgColors = ImageColorGenerator(bimg)
重置词云图颜色:wordcloud.recolor(color_func=bimgColors)

完整代码:

import os;
import os.path;
import codecs;
filePaths=[];
fileContents=[];
for root,dirs,files in os.walk(
        "C:\\Users\\lls\\Desktop\\Python\\aa"
        ):
    for name in files:
        filePath = os.path.join(root,name);
        filePaths.append(filePath);
        f=codecs.open(filePath,'r','gb18030',errors='ignore')
        fileContent=f.read()
        f.close()
        fileContents.append(fileContent)
import pandas;
corpos=pandas.DataFrame({
        'filePath':filePaths,
        'fileContent':fileContents
        }) 
import jieba
segments=[]
filePaths=[]
stopwords = pandas.read_csv(
        "C:\\Users\\lls\\Desktop\\Python\\DM\\StopwordsCN.txt",
        encoding='utf8',
        index_col=False)
for index,row in corpos.iterrows():
    filePath = row['filePath']
    fileContent=row['fileContent']
    segs=jieba.cut(fileContent)
    for seg in segs:
        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
                    });
    import numpy;
    segStat=segmentDataFrame.groupby(
            by="segment"
            )["segment"].agg({
                    "计数":numpy.size
                    })
    text=segStat.reset_index(
            drop=False
            );
from wordcloud import WordCloud
import matplotlib.pyplot as plt
wordcloud = WordCloud( 
    font_path="C:\\Users\\lls\\Desktop\\Python\\DM\\simhei.ttf", 
    background_color="black"
)
words = text.set_index('segment').to_dict()
wordcloud.fit_words(words['计数'])
plt.imshow(wordcloud)

from scipy.misc import imread
import matplotlib.pyplot as plt
from wordcloud import WordCloud,ImageColorGenerator
bimg = imread("C:\\Users\\lls\\Desktop\\aaa.png")
wordcloud = WordCloud(
    background_color="white", 
    mask=bimg, font_path="C:\\Users\\lls\\Desktop\\simhei.ttf"
)

wordcloud = wordcloud.fit_words(words['计数'])
plt.figure(
        num=None,
        figsize=(8,6),dpi=80,
        facecolor='w',edgecolor='k'
        )

bimgColors = ImageColorGenerator(bimg)

plt.axis("off")
plt.imshow(wordcloud.recolor(color_func=bimgColors))
plt.show()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章