• 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()
    
    
    运行效果如下:
    

    生产图片文件:

     

  • 相关阅读:
    Android13 串口控制是能wifi adb实现
    数据库基础
    6部署AD域
    Jupyter使用技巧
    Percona监控数据库解决方案
    [计算估计网络]十六、DHCP协议
    什么是APS?APS+MES如何解决生产难题?
    树莓派4b linux内核调试(jtag、kgdb)
    一文详解训练LLM流程
    C语言不可不敲系列:跳水比赛排名问题
  • 原文地址:https://blog.csdn.net/flysh05/article/details/133523301