美文网首页
结巴分词和词云图——天龙八部人物提取并制作图云

结巴分词和词云图——天龙八部人物提取并制作图云

作者: wendy云泽 | 来源:发表于2019-08-03 21:11 被阅读0次

    代码与数据链接:https://pan.baidu.com/s/1425DckPlqrGyUFW6APnxpQ

    提取码:sbmc

    1. 导入数据

    import pandas as pd

    import os

    os.chdir('./')

    character =open('天龙八部人物表.txt',encoding='utf-8').read()

    2. '''添加词性'''

    import re

    data = re.split(r'\s+|:|,', character)

    data = pd.DataFrame(data, columns=['姓名'])

    #查看data

    print(data.head())

    data['词性'] ='nr'

    #将对象写入Excel工作表。

    data.to_excel('天龙八部人物分词.xlsx', index=False, header=None)

    3.将天龙八部这本书进行分词

    '''添加自定义词库'''

    import jieba

    # jieba.enable_parallel(4)

    jieba.load_userdict('天龙八部人物词典.txt')

    '''加载停用词库'''

    stopwords = [line.rstrip()for linein open('停用词表.txt', encoding='utf-8')]

    '''分词'''

    def seg_sentence(sentence):

    sentence_seged = jieba.cut(sentence.strip())

    outstr =''

        for wordin sentence_seged:

    if wordnot in stopwords:

    if word !='\t':

    outstr += word

    outstr +=" "

        return outstr

    inputs =open('天龙八部.txt', 'r', encoding='GB18030')

    outputs =open('天龙八部分词.txt', 'w',encoding='utf-8')

    for linein inputs:

    line_seg = seg_sentence(line)

    outputs.write(line_seg +'\n')

    outputs.close()

    inputs.close()

    4.提取关键字

    #

    #

    '''加载分词后的文本'''

    text =open('天龙八部分词.txt', encoding='utf-8').read()

    '''指定词性,提取关键词:TF-IDF'''

    import jieba.analyse

    n =100          #指定关键词数量

    result = jieba.analyse.extract_tags(text, topK=n, withWeight=True, allowPOS=('nr',))

    #返回关键词和权重

    result[:10]#打印前10个最重要的人物

    print(result)

    结果如下:

    5.利用关键词制作词云

    '''词云关键词'''

    keywords =dict()

    for iin result:

    keywords[i[0]] = i[1]

    '''设置词云属性'''

    from PILimport Image

    import numpyas np

    from wordcloudimport WordCloud, ImageColorGenerator

    import matplotlib.pyplotas plt

    image = Image.open('图片.png') #这里你可以随意选择你想绘制的图云图案。

    graph = np.array(image)

    wc = WordCloud(font_path='/Library/Fonts/simsun.ttc', #设置字体

                  background_color='White',          #设置背景颜色

                  max_words=n,                      #设置词云显示的最大词数

                  mask=graph)#设置背景样式

    #注:这里需要查看本地是否存在该字体,否则会报错:OSError: cannot open resource,在Windows环境,字体一般位于C:\WINDOWS\Fonts文件夹下。用户可以到此文件夹中查看Python程序中指定的字体是否存在。

    Python程序中直接写类似华文行楷.ttf、微软简粗黑.TTF等中文名称的字体会出错。查看对应字体英文名称的方法很简单,我们可以选中相应字体,右击属性项即可找到。


    '''生成词云'''

    wc.generate_from_frequencies(keywords)#生成词云

    plt.imshow(wc)

    image_color = ImageColorGenerator(graph)#从背景图片生成颜色值

    plt.imshow(wc.recolor(color_func=image_color))

    plt.axis("off")#不显示坐标轴

    plt.show()

    wc.to_file('词云.jpg')#保存结果到本地

    词云.jpg

    下一步改进:使用命名实体识别技术来自动提取关键人物而非自定义词典。

    词云的制作可参考:词云wordcloud入门示例:https://www.cnblogs.com/jlutiger/p/9176517.html

    相关文章

      网友评论

          本文标题:结巴分词和词云图——天龙八部人物提取并制作图云

          本文链接:https://www.haomeiwen.com/subject/osjsdctx.html