• NLP工具学习(1)Thulac分词工具与WordCloud词云


    0 前言

    数据集:某比赛数据集

    1 下载安装

    均使用清华源
    thulac

    pip install thulac -i https://pypi.tuna.tsinghua.edu.cn/simple
    
    • 1

    wordcloud

    pip install -i https://pypi.tuna.tsinghua.edu.cn/simple wordcloud
    
    • 1

    2 thunlac分词

    user_path
    设置用户词典,用户词典中的词会被打上uw标签。词典中每一个词一行,UTF8编码
    t2s
    默认False, 是否将句子从繁体转化为简体
    just_seg
    默认False, 时候只进行分词,不进行词性标注
    ufilter
    默认False, 是否使用过滤器去除一些没有意义的词语,例如“可以”。
    model_path
    设置模型文件所在文件夹,默认为models /
    separator
    默认为‘_’, 设置词与词性之间的分隔符

    thulac(seg_only=True).cut_f('../analyse/input.txt', '../analyse/output.txt')
    
    • 1

    3 WordCloud词云

        cloud = WordCloud(font_path='msyh.ttc', background_color='white', width=800, height=800, margin=2, stopwords=stopwords)
        # cloud.generate(text='通过 大力 发展 社区 教育 , 使 我省 全民 终身 学习 的 教育 体系 已 深入人心 。')
        cloud.generate(words_str)
        cloud.to_file('../figure//word_cloud.png')
    
    • 1
    • 2
    • 3
    • 4

    效果
    在这里插入图片描述

    4 可能遇到的问题

    thulac源码版本与python版本不兼容,报错
    解决方法:
    修改源码

    init.py

            input_f = open(input_file, 'r', encoding='utf8')
            output_f = open(output_file, 'w', encoding='utf8')
    
    • 1
    • 2

    GBTangingDecoder.py

            start = time.perf_counter()
    
    • 1

    5 完整代码

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    import tqdm
    import re
    import string
    import zhon.hanzi
    import cv2
    import os
    from thulac import thulac
    from wordcloud import WordCloud
    
    
    # 常量
    wordcloud_open = True
    
    
    # 加载数据集
    train_dataset = pd.read_csv('../data/train.csv', delimiter='\t', encoding='utf8')
    datas = train_dataset['text']
    labels = train_dataset['label']
    print(labels.value_counts())
    
    
    # 保存为input.txt文件
    with open('../analyse/input.txt', 'w', encoding='utf8') as f:
        for line in datas.values.tolist():
            f.write(line + '\n')
    
    
    # 显示并保存词云
    def show_save_word_cloud(words_str):
        # 加载停用词表
        stopwords = set()
        words = [word.strip() for word in open('../data/stopwords_zh.txt', 'r', encoding='utf8').readlines()]
        stopwords.update(words)
    
        # 词云
        cloud = WordCloud(font_path='msyh.ttc', background_color='white', width=800, height=800, margin=2, stopwords=stopwords)
        # cloud.generate(text='通过 大力 发展 社区 教育 , 使 我省 全民 终身 学习 的 教育 体系 已 深入人心 。')
        cloud.generate(words_str)
        cloud.to_file('../figure//word_cloud.png')
        img = cv2.imread('../figure/word_cloud.png')
        cv2.imshow('WordCloud', img)
        k = cv2.waitKey(0)
        if k == 27:  # ESC
            cv2.destroyAllWindows()
    
    
    # thulac分词
    if not os.path.exists('../analyse/output.txt'):
        thulac(seg_only=True).cut_f('../analyse/input.txt', '../analyse/output.txt')
    else:
        corpus = []
        all_words = ''
        with open('../analyse/output.txt', 'r', encoding='utf8') as f:
            for line in f.readlines():
                corpus.append(line.strip('\n'))
                all_words = all_words + ' ' + line.strip('\n')
        if wordcloud_open:
            show_save_word_cloud(all_words)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
  • 相关阅读:
    Redis学习笔记17:基于spring data redis及lua脚本批处理scan指令查询永久有效的key
    jemter使用和优化
    Spring MVC中如何获取Request,Response对象方法呢?
    【好书推荐】《Python编程:从入门到实践(第2版)》
    Pandas 2.2 中文官方教程和指南(十七)
    SpringBoot-基础篇复习(全)
    基于Java的流浪动物救助平台设计与实现(源码+lw+部署文档+讲解等)
    C#和西门子PLC使用Udp通信
    30天Python入门(第十一天:深入了解Python中的函数)
    C理解(四):链表
  • 原文地址:https://blog.csdn.net/m0_46275020/article/details/126488443