wordcloud库和jieba库的使用

文章目录

  • wordcloud库的简单示范
  • 使用wordcloud库报错记录
  • anaconda安装第三方jieba库
  • jieba库的简单示范
  • [任务 1:三国演义中的常见词汇分布在"三国"这两个隶书字上,出现频率高的词字体大](#任务 1:三国演义中的常见词汇分布在“三国"这两个隶书字上,出现频率高的词字体大)
  • [任务 2:三国演义中出现频率前十的人名。必须是以下这十个名字,名字组成心形](#任务 2:三国演义中出现频率前十的人名。必须是以下这十个名字,名字组成心形)

wordcloud库的简单示范

python 复制代码
from wordcloud import WordCloud
from wordcloud import ImageColorGenerator
from PIL import Image
import numpy as np

txt = "Python Java C++ JavaScript PHP Ruby Swift Kotlin Go Rust"     # 示例文本

# 创建词云对象,配置参数
c = WordCloud(
    width=400,
    height=400,
    font_path=None,
    repeat=True, # 表示单词是否可以重复出现
    mask=np.array(Image.open("love.png")), # 给词云生成轮廓用的参数,不需要做成轮廓的背景应为白色
    background_color="white", # 背景颜色
    max_words=150 # 词云的最大单词数
)
c.generate(txt)  # 指定词云的文本文件
c.to_file("词云图.jpg")    # 将生成的词云文件输入到一个文件中

使用wordcloud库报错记录

在使用wordcloud库的时候,运行报错:ValueError: Only supported for TrueType fonts

解决方案:去升级pillow库!!!

anaconda安装第三方jieba库

  1. 打开Anaconda Prompt,并进入目标环境。输入 activate 环境名
  2. 输入 pip install jieba
  3. 如果因为网络原因而下载失败,可使用清华大学镜像(99.9%解决下载失败问题):
    pip install 名称 -i https://pypi.tuna.tsinghua.edu.cn/simple

jieba库的简单示范

python 复制代码
import jieba

s = "中国是一个伟大的国家"

s1 = jieba.lcut(s) # 精确模式
print(s1)

s2 = jieba.lcut(s, cut_all=True) # 全模式
print(s2)

s3 = jieba.lcut_for_search(s) # 搜索引擎模式
print(s3)

# jieba.add_word(str)   向分词词典添加新词 str

任务 1:三国演义中的常见词汇分布在"三国"这两个隶书字上,出现频率高的词字体大

python 复制代码
from wordcloud import WordCloud
from wordcloud import ImageColorGenerator
from PIL import Image
import numpy as np
from jieba import *

def getText(filename):
    text = open("{}".format(filename), encoding='utf-8').read()
    sign = '''!~·@¥......*""''\n(){}【】;:"'「,」。-、?\u3000\ufeff'''
    for ch in sign: # 特殊符号替换成空格
        text = text.replace(ch, ' ')
    return text

def wordCount(text, N):
    words = lcut(text) # 精确分词
    counts = {} # 字典类型

    for word in words:
        if len(word) < 2:
            continue
        if word not in counts:
            counts[word] = 0
        else:
            counts[word] += 1

    temp = sorted(counts.items(), key=lambda d: d[1], reverse=True) # 按计数值逆序排序
    result = dict(temp[1:N+1])

    return result

def drawWordCloud(data, N):
    # 创建词云对象,配置参数
    c = WordCloud(
        width=400,
        height=400,
        font_path="C:\Windows\Fonts\STXINGKA.TTF", # 设置字体
        repeat=False,  # 表示单词是否可以重复出现
        mask=np.array(Image.open("三国.png")),  # 给词云生成轮廓用的参数,不需要做成轮廓的背景应为白色
        background_color="white",  # 背景颜色
        max_words=N  # 词云的最大单词数
    )
    result_str = ' '.join(data.keys())
    c.generate(result_str)  # 指定词云的文本文件
    c.to_file("自制结果1.jpg")  # 将生成的词云文件输入到一个文件中

if __name__ == '__main__':
    N = 200
    text = getText('三国演义utf8.txt')
    result = wordCount(text, N)
    drawWordCloud(result, N)

运行结果:

任务 2:三国演义中出现频率前十的人名。必须是以下这十个名字,名字组成心形

十个名字:刘备、赵云、关羽、周瑜、曹操、孔明、孙权、司马懿、张飞、吕布

python 复制代码
from wordcloud import WordCloud
from wordcloud import ImageColorGenerator
from PIL import Image
import numpy as np
from jieba import *

def getText(filename):
    text = open("{}".format(filename), encoding='utf-8').read()
    sign = '''!~·@¥......*""''\n(){}【】;:"'「,」。-、?\u3000\ufeff'''
    for ch in sign: # 特殊符号替换成空格
        text = text.replace(ch, ' ')
    return text

def wordCount(text, N):
    words = lcut(text) # 精确分词
    counts = {} # 字典类型
    name = ["刘备", "赵云", "关羽", "周瑜", "曹操", "孔明", "孙权", "司马懿", "张飞", "吕布"]

    for word in words:
        if word in name:
            if word not in counts:
                counts[word] = 0
            else:
                counts[word] += 1
        else:
            continue

    temp = sorted(counts.items(), key=lambda d: d[1], reverse=True) # 按计数值逆序排序
    result = dict(temp[:N])

    return result

def drawWordCloud(data, N):
    # 创建词云对象,配置参数
    c = WordCloud(
        width=400,
        height=400,
        font_path="C:\Windows\Fonts\STXINGKA.TTF", # 设置字体
        repeat=False,  # 表示单词是否可以重复出现
        mask=np.array(Image.open("love.png")),  # 给词云生成轮廓用的参数,不需要做成轮廓的背景应为白色
        background_color="white",  # 背景颜色
        max_words=N  # 词云的最大单词数
    )
    result_str = ' '.join(data.keys())
    c.generate(result_str)  # 指定词云的文本文件
    c.to_file("自制结果2.jpg")  # 将生成的词云文件输入到一个文件中

if __name__ == '__main__':
    text = getText('三国演义utf8.txt')
    result = wordCount(text, 10)
    drawWordCloud(result, 10)

运行结果:

相关推荐
紫雾凌寒40 分钟前
计算机视觉 |解锁视频理解三剑客——TimeSformer
python·深度学习·神经网络·计算机视觉·transformer·timesformer
程序员杰哥1 小时前
测试用例详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
go54631584657 小时前
本地部署 GitHub 上的 Python 人脸识别项目
开发语言·python·github
FreakStudio8 小时前
手把手教你用 MicroPython 玩转幻尔串口舵机,代码+教程全公开
python·嵌入式·大学生·面向对象·技术栈·电子diy·电子计算机
tekin8 小时前
基于 Python 开发在线多人游戏服务器案例解析
服务器·python·游戏·在线多人游戏服务器
让学习成为一种生活方式10 小时前
libGL.so.1: cannot open shared object file: No such file or directory-linux022
linux·开发语言·python
java1234_小锋10 小时前
一周学会Flask3 Python Web开发-Jinja2模板继承和include标签使用
python·flask·flask3
图书馆钉子户10 小时前
from flask_session import Session 为什么是Session(app)这么用?
python·flask·mybatis
一只蜗牛儿11 小时前
Sherpa-ONNX:说话人识别与语音识别自动开启(VAD)+ Python API 完整指南
人工智能·python·语音识别
结衣结衣.11 小时前
【OpenCV】入门教学
图像处理·人工智能·python·opencv