用 Python 实现一个词云生成器

在日常工作和学习中,我们经常需要分析文本内容,例如文章、日志或者评论。词云(Word Cloud)是一种非常直观的可视化方式,它能把文本中出现频率高的词显示得更大,帮助我们快速抓住核心信息。本文将介绍如何用 Python 实现一个带 GUI 的词云生成器


一、程序功能

我们的词云生成器功能包括:

  1. 选择本地文本文件(txt 格式)
  2. 读取文本内容
  3. 根据词频生成词云
  4. 在 GUI 窗口中显示词云
  5. 支持清空和重新生成

二、程序代码

import tkinter as tk
from tkinter import filedialog
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import os
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

canvas = None

def select_file():
    path = filedialog.askopenfilename()
    if not path:
        return

    title.config(text=os.path.basename(path))
    text = read_text(path)

    # 生成词云
    wordcloud = WordCloud(
        font_path="msyh.ttc",  # 中文字体
        width=800,
        height=400,
        background_color='white',
    ).generate(text)

    # 清空旧画布
    global canvas
    for widget in frame.winfo_children():
        widget.destroy()

    # 创建 matplotlib Figure
    fig, ax = plt.subplots(figsize=(8,4))
    ax.imshow(wordcloud, interpolation='bilinear')
    ax.axis('off')

    # 把 Figure 嵌入 Tkinter
    canvas = FigureCanvasTkAgg(fig, master=frame)
    canvas.draw()
    canvas.get_tk_widget().pack()

def cancel():
    title.config(text="选择文件")
    global canvas
    if canvas:
        canvas.get_tk_widget().destroy()
        canvas = None

def read_text(path):
    with open(path, "r", encoding="utf-8") as f:
        return f.read()

# 创建窗口
win = tk.Tk()
win.geometry('900x600')
win.title("文本词云生成器")

# 显示文件名的标签
title = tk.Label(win, text="选择文件", font=("黑体",24))
title.pack(pady=10)

# 按钮
btn_select = tk.Button(win, text="选择文件", command=select_file)
btn_cancel = tk.Button(win, text="返回", command=cancel)
btn_select.pack(pady=5)
btn_cancel.pack(pady=5)

# 用 Frame 放置词云图
frame = tk.Frame(win)
frame.pack(fill="both", expand=True, padx=10, pady=10)

win.mainloop()

三、代码解析

  1. GUI 界面
  • 使用 Tkinter 创建主窗口、Label 和 Button
  • Label 用于显示当前选择的文件名
  • Button 分别用于选择文件和清空显示
  1. 读取文本
  • read_text() 函数读取文本内容
  • 读取完成后传入 WordCloud 生成词云
  1. 生成词云
  • WordCloud 根据词频生成词云
  • font_path="msyh.ttc" 用于显示中文
  • widthheight 控制图像大小
  • background_color='white' 设置背景颜色
  1. 显示词云
  • 用 matplotlib 绘制词云
  • FigureCanvasTkAgg 嵌入 Tkinter 窗口
  • 每次生成新的词云前,清空旧的图像

四、程序使用方法

  1. 点击“选择文件”,选择本地 txt 文件
  2. Label 显示文件名,词云显示在窗口中
  3. 点击“返回”按钮可以清空词云
  4. 再次选择其他文件,可以生成新的词云

五、打包成 exe 文件

如果你希望别人不用安装 Python 也能运行程序,可以打包成 Windows 可执行文件(.exe)。

1️⃣ 安装 PyInstaller

pip install pyinstaller

2️⃣ 打包命令

pyinstaller -F -w wordcloud_app.py

说明:

  • -F:打包成单个 exe 文件
  • -w:不显示命令行窗口(GUI 程序用)

3️⃣ 打包完成

  • 可执行文件生成在 dist/wordcloud_app.exe
  • 双击即可运行,不需要安装 Python
  • 如果程序里用到字体文件 msyh.ttc,建议和 exe 放在同一目录

4️⃣ 注意事项

  • 打包后的 exe 文件通常在 20MB~50MB 左右,因为包含了 Python 解释器和所有依赖库
  • 确保程序在 Python 环境里可以正常运行后再打包

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇