python 统计文本字数 生成词云图

程序采用wordcloud、jieba分词、matplotlib绘制图像的模块

02.py

# 题目二
# 请你设计一个统计字数的工具,工具要求如下:
# 1、统计的是任意文本文件(txt)内容的字数(不算空格和符号)
# 2、用词云图将统计的字显示出来

from wordcloud import WordCloud
import matplotlib.pyplot as plt  #绘制图像的模块
import  jieba                    #jieba分词

class Myword:
    def __init__(self, url):
        self.url = url

    # 统计字数
    def statistics(self):
        try:
            # 由于书名不是英文,要加上 encoding='utf8'
            with open(self.url, encoding='GBK') as f:
               #读取文件的所有行
                lines = f.readlines()
        except FileNotFoundError:
            print("文件读取错误!!")

        content = ''
        words = []
        words_count = {}
        for line in lines:
            # 去除空格
            line = line.strip()
            # 如果是空行,则跳过
            if len(line) == 0:
                continue
            # 合并所有行,统计全部字数
            content = content + line
            # 统计每一字出现的个数
            for x in range(0, len(line)):
                # 如果字符第一次出现 加入到字符数组中
                if not line[x] in words:
                    words.append(line[x])
                # 如果是字符第一次出现 加入到字典中
                if line[x] not in words_count:
                    words_count[line[x]] = 1
                # 出现次数加一
                words_count[line[x]] += 1

        print('全文共有%d个字' % len(content))
        print('一共有%d个不同的字' % len(words))
        print(words_count)
        for a in words_count.keys():
            print("[", a, "] 共出现 ", words_count[a], "次")

        f.close()



    def word_cloud(self):
        f = open(self.url, 'r', encoding='GBK').read()

        # 结巴分词,生成字符串,wordcloud无法直接生成正确的中文词云
        cut_text = " ".join(jieba.cut(f))

        wordcloud = WordCloud(
            # 设置字体,不然会出现口字乱码,文字的路径是电脑的字体一般路径,可以换成别的
            font_path="C:/Windows/Fonts/simfang.ttf",
            # 设置了背景,宽高
            background_color="white", width=1000, height=880).generate(cut_text)

        plt.imshow(wordcloud, interpolation="bilinear")
        plt.axis("off")
        plt.show()
        wordcloud.to_file("test.png")


if __name__ == '__main__':
    url = 'test.txt'
    s = Myword(url)
    s.statistics()
    s.word_cloud()

test.txt

2019年5月29日上午10点,本科教学审核评估专家、贵州财经大学副校长缪坤和教授走访了
学校教学督导团,在教育研究与评建中心会议室对督导团团长邹勇、督导团成员
董秀红、杨红芸、穆伯祥等进行了访谈。
访谈中,邹勇团长从督教、督学、督管以及开展教师教学能力培训等方面汇报了
校督导团开展的工作。听完汇报后,缪坤和教授查看了督导团近两年的督导工
作汇编、督导工作简报、督导工作研究成果,就“互联网+”背景下如何进一步
做好教师课堂教学督导工作与大家进行了深入的交流,并对教学督导队伍建设做了指导。

结果展示如下图

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鼎上西瓜刀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值