• Python使用词云图展示


    网上看到一个txt文本信息,共2351条饭否记录,据说是微信之父每天发的饭否记录,其实我不知道什么是饭否。我读取这个文本内容,展示到词语图上。之前也使用过,但是好久没有玩Python了,称假期空闲,练习练习。开始发行“通过网页”变成了高频词汇,一看源文本文件,发行每条记录的后面都包含“ 2010-11-26 13:59 通过网页”,这样通过网页肯定是高频词了,所有重新处理了源文本信息,使用正则表达式式,提前时间节点前的任意字符。使用的正则表达式:.+(?=(\d{4}\-\d{2}\-\d{2}))

    提取信息如下:

    找一个背景,网上找奋斗图片,去掉背景色,裁剪人物。

    完整代码:

    from os import path
    from PIL import Image
    import numpy as np
    import matplotlib.pyplot as plt
    import os
    import chardet
    
    from wordcloud import WordCloud, STOPWORDS
    
    # get data directory (using getcwd() is needed to support running example in generated IPython notebook)
    d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()
    print(d)
    
    # Read the whole text.
    # text = open(path.join(d, 'ZXL.txt'), encoding='utf-8', errors='ignore').read()
    with open(path.join(d, 'ZXL.txt'), 'rb') as f:
        raw_data = f.read()
        result = chardet.detect(raw_data)
        use_encoding = result['encoding']
    
    # 查看文本使用的编码
    print(use_encoding) # utf-8
    text = open(path.join(d, 'ZXL.txt'), 'r', encoding=use_encoding).read()
    
    # read the mask image
    fight_mask = np.array(Image.open(path.join(d, "fight.png")))
    
    # 指定字体文件路径
    font_path = r'C:\Windows\Fonts\方正粗黑宋简体.ttf'
    
    # 创建词云图对象并设置字体
    stopwords = set(STOPWORDS)
    
    wc = WordCloud(background_color="white",
                   max_words=6000, mask=fight_mask,
                   font_path=font_path,
                   stopwords=stopwords,
                   contour_width=3,
                   contour_color='steelblue')
    
    # generate word cloud
    wc.generate(text)
    
    # store to file
    wc.to_file(path.join(d, "ZXL_example.png"))
    
    # show
    plt.imshow(wc, interpolation='bilinear')
    plt.axis("off")
    plt.show()
    
    
    运行效果如下:
    

    生产图片文件:

     

  • 相关阅读:
    容器化运维:构建高可用RabbitMQ集群的Docker Compose指南
    Docker简单使用总结
    开始Linux之路
    基于51单片机的简易交通灯仿真代码讲解
    发送短信验证码执行登录操作
    啊?现在初级测试招聘都要求会自动化了?
    华为机试真题 C++ 实现【矩阵最大值】
    WebGoat搭建和Yakit学习
    【计算机网络】第一张:计算机网络概述
    历时一年,论文终于被国际顶会接收了
  • 原文地址:https://blog.csdn.net/flysh05/article/details/133523301