栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

22年春疫情期间楼栋搬运志愿者“词云图”

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

22年春疫情期间楼栋搬运志愿者“词云图”

书接上回,22年春疫情期间楼栋搬运志愿者搬运信息统计,为更好的展示搬运者搬运频率,现将搬运志愿者搬运的频率以“词云图”的形式展示出来。

一、原始数据

二、代码实现
import jieba  # 结巴分词
from wordcloud import WordCloud  # 词云展示库
from PIL import Image  # 图像处理库
import numpy as np  # 持多维数组和矩阵运算
import matplotlib.pyplot as plt  # 图像展示库

import re    # 导入re正则表达式
import xlrd  # 引入Excel库的xlrd


def fun_data_pro(path1):
    """
    1)读取excel所有sheet中D2的内容,构成一个字符串。
    2)去除该字符串中所有括号及括号内的内容。
    3)返回该处理后的内容

    :param path1: 存放原始excel的路径
    :return:    存放处理后的数据内容
    """
    book = xlrd.open_workbook(path1)
    len_book_nsheets = book.nsheets    # 获取excel表中sheet的个数
    # print("The number of worksheets is {0}".format(book.nsheets))
    # book_sheet_names = book.sheet_names()
    # print("Worksheet name(s): {0}".format(book.sheet_names()))

    total_str = ''                     # 定义一个字符串,字符串内存放所有sheet中D2的内容之和
    for i in range(len_book_nsheets):
        sh = book.sheet_by_index(i)
        # print("{0} {1} {2}".format(sh.name, sh.nrows, sh.ncols))
        # print("Cell D2 is {0}".format(sh.cell_value(rowx=1, colx=3)))
        total_str = total_str + sh.cell_value(1, 3)

    # 去除括号及括号内的内容
    p = re.compile(r'[(](.*?)[)]', re.S)
    new_total_str1 = re.sub(p, '', total_str)      # 去除中文括号及括号内的内容
    p2 = re.compile(r'[(](.*?)[)]', re.S)
    new_total_str2 = re.sub(p2, '', new_total_str1)  # 去除英文括号及括号内的内容

    with open('data_after_pro.txt', 'w') as f:    # 设置文件对象
        f.write(new_total_str2)                   # 将字符串写入文件中

    return new_total_str2

fun_data_pro(r'D:u_careeri_coderi_python抗疫搬运日记搬运(分发抗疫物资+分发生活物资).xlsx')

# 读取文本内容
with open('data_after_pro.txt', 'r', encoding="gbk") as f:
    file = f.read()  # 将文本读取为整个字符串,readlines可以按行读取

# 进行分词
data_cut =jieba.cut(file, cut_all=False)  # 精确模式分词
print(data_cut)

stop_words = []  # 停词列表
# 创建空列表
with open("baidu_stopwords.txt", 'r', encoding='utf-8') as f:
    for line in f:
        if len(line) > 0:
            stop_words.append(line.strip())  # 把停词追加到stop_words列表中

data_result = [i for i in data_cut if i not in stop_words]  # 获取需要的词

print(data_result)

text = " ".join(data_result).replace("n", "")  # 连接成字符串2print(text)
print(text)

images = np.array(Image.open("拇指.jpg"))
wc = WordCloud( #设置字体,不指定就会出现乱码,这个字体文件需要下载
               font_path="演示悠然小楷.ttf", background_color="black", max_words=5000, mask=images)
# 生成词云图
wc.generate(text)
# 保存词云图
wc.to_file("11号楼抗疫英雄.jpg")  # 保存图片
#  展示
plt.imshow(wc)  # 对图片进行处理,并显示其格式
plt.axis("off")  # 关闭坐标轴
plt.show()  # 将图片显示出来



参考链接:
实战|Python轻松实现绘制词云图(附详细源码)
最全中文停用词表(可直接复制)
停用词表链接
演示悠然小楷.ttf
python xlrd模块快速上手
python如何读取excel表数据
Python读取、写入txt文件
python 正则匹配括号内的内容及删除括号内内容

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/916178.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号