python:wordcloud
# encoding: utf-8 # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看言語成了邀功盡責的功臣還需要行爲每日來值班嗎 # 描述 # Author : geovindu,Geovin Du 涂聚文. # IDE : PyCharm 2024.3.6 python 3.11 # os : windows 10 # database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j # Datetime : 2026/7/28 22:10 # User : geovindu # Product : PyCharm # Project : Pysimple # File : stylecloud_full.py import os import re import random import numpy as np import jieba import pandas as pd from io import BytesIO from PIL import Image from cairosvg import svg2png from wordcloud import WordCloud from palettable import palette as palettable_palette from fa6_icons import svgs DEFAULT_FONT_PATH None # FontAwesome 图标处理 def _get_fa_svg(icon_name: str) - str: parts icon_name.strip().split() if len(parts) ! 2: raise ValueError(icon_name格式示例: fas fa-heart) style, name parts style_map {fas: solid, far: regular, fab: brands} if style not in style_map: raise ValueError(f不支持的样式: {style}) style_name style_map[style] name name.replace(fa-, ).replace(-, _) try: svg_data str(getattr(svgs, name).get(style_name)) if not svg_data: raise ValueError(f图标 {icon_name} 不存在) return svg_data except Exception as e: raise RuntimeError(f图标 {icon_name} 获取失败请检查名称) from e def _fa_icon_to_mask(icon_name: str, size: int 512) - np.ndarray: svg_text _get_fa_svg(icon_name) svg_text re.sub(rwidth\d, fwidth{size}, svg_text) svg_text re.sub(rheight\d, fheight{size}, svg_text) png_bytes svg2png(bytestringsvg_text.encode(), output_widthsize, output_heightsize) img Image.open(BytesIO(png_bytes)).convert(L) arr np.array(img) mask np.where(arr 128, 255, 0).astype(np.uint8) return mask # 停用词 脏数据清理 def _load_stopwords(filepath: str None) - set: stopwords set() if filepath and os.path.exists(filepath): with open(filepath, r, encodingutf-8) as f: for line in f: w line.strip() if w: stopwords.add(w) return stopwords def _is_useless_single_char(word: str) - bool: 自动清理无意义单字、标点、数字 if len(word) ! 1: return False # 单字黑名单标点、数字、常见无意义单字 useless_chars r。【】{}、·~!#$%^*()_-|\/0123456789 return word in useless_chars def _filter_stopwords(word_list: list, stopwords: set) - list: result [] for w in word_list: w w.strip() if not w: continue if w in stopwords: continue if _is_useless_single_char(w): continue result.append(w) return result # CSV词频读取接口 新增 def load_wordfreq_from_csv(csv_path: str, word_colword, freq_colfreq) - dict: 读取csv词频文件 :param csv_path: csv路径 :param word_col: 词汇列名 :param freq_col: 频次列名 :return: {词汇:频次} df pd.read_csv(csv_path, encodingutf-8) df df.dropna(subset[word_col, freq_col]) word_freq {} for _, row in df.iterrows(): word str(row[word_col]).strip() freq int(row[freq_col]) if not _is_useless_single_char(word): word_freq[word] freq return word_freq # 配色函数 def _get_palette_color_func(palette_name: str, random_state): import palettable parts palette_name.split(.) obj palettable for part in parts: obj getattr(obj, part) colors_rgb obj.colors def color_func(word, font_size, position, orientation, random_staterandom_state, **kwargs): idx random_state.randint(len(colors_rgb)) r, g, b colors_rgb[idx] return frgb({r},{g},{b}) return color_func # 文本预处理 def _process_text( text: str None, text_path: str None, word_freq: dict None, csv_path: str None, stopwords: set None, is_chinese: bool True ) - str | dict: # 优先读取CSV词频 if csv_path is not None: word_freq load_wordfreq_from_csv(csv_path) if stopwords: word_freq {k: v for k, v in word_freq.items() if k not in stopwords} return word_freq if word_freq is not None: if stopwords: word_freq {k: v for k, v in word_freq.items() if k not in stopwords} return word_freq if text_path and os.path.exists(text_path): with open(text_path, r, encodingutf-8) as f: raw f.read() elif text: raw text else: raise ValueError(text / text_path / word_freq / csv_path 必须传入其一) if is_chinese: words jieba.lcut(raw) else: words raw.split() if stopwords: words _filter_stopwords(words, stopwords) return .join(words) # 核心API gen_stylecloud def gen_stylecloud( text: str None, text_path: str None, word_freq: dict None, csv_path: str None, # 新增csv词频文件 icon_name: str None, mask_img: np.ndarray None, palette: str None, background_color: str white, transparent_bg: bool False, # 新增开启透明背景PNG font_path: str DEFAULT_FONT_PATH, output_name: str stylecloud.png, size: tuple (512, 512), max_font_size: int 200, scale: float 2, prefer_horizontal: float 0.7, random_state: int 42, contour_width: float 0, contour_color: str #333333, is_chinese: bool True, stopwords_path: str None, ): rng np.random.RandomState(random_state) stopwords _load_stopwords(stopwords_path) if stopwords_path else None mask mask_img if mask is None and icon_name is not None: mask _fa_icon_to_mask(icon_name, sizesize[0]) processed_data _process_text( texttext, text_pathtext_path, word_freqword_freq, csv_pathcsv_path, stopwordsstopwords, is_chineseis_chinese ) # 透明背景时强制背景为None bg_color None if transparent_bg else background_color wc WordCloud( widthsize[0], heightsize[1], font_pathfont_path, background_colorbg_color, maskmask, max_font_sizemax_font_size, scalescale, prefer_horizontalprefer_horizontal, contour_widthcontour_width, contour_colorcontour_color, random_staterng ) if isinstance(processed_data, dict): wc.generate_from_frequencies(processed_data) else: wc.generate(processed_data) if palette is not None: color_func _get_palette_color_func(palette, rng) wc.recolor(color_funccolor_func, random_staterng) # 保存 wc.to_file(output_name) print(f✅ 生成完成: {output_name}) return wc # 【批量生成脚本】主入口 if __name__ __main__: # 配置区域 FONT rC:\Windows\Fonts\STXIHEI.TTF OUTPUT_DIR ./batch_output os.makedirs(OUTPUT_DIR, exist_okTrue) test_text 人工智能 大模型 Python 数据分析 词云 机器学习 深度学习 NLP 计算机视觉 向量数据库 Agent RAG 云计算 大数据 算法 开发 编程 架构 # 批量循环配置 # 1. 多种FontAwesome图标 icon_list [ fas fa-heart, fas fa-code, fas fa-star, fas fa-globe, fas fa-lightbulb ] # 2. 多种配色方案 palette_list [ cartocolors.diverging.TealRose_7, colorbrewer.qualitative.Set2_8, colorbrewer.qualitative.Dark2_8, matplotlib.Viridis_10 ] # 批量循环生成 idx 1 for icon in icon_list: for palette in palette_list: out_file os.path.join(OUTPUT_DIR, fcloud_{idx}_{icon.split()[-1]}_{palette.split(.)[-1]}.png) gen_stylecloud( texttest_text, font_pathFONT, icon_nameicon, palettepalette, background_colorblack, transparent_bgFalse, output_nameout_file, is_chineseTrue, prefer_horizontal0.6 ) idx 1 # 独立测试示例 # 示例1CSV词频文件读取 # gen_stylecloud( # csv_pathword_freq.csv, # font_pathFONT, # icon_namefas fa-star, # transparent_bgTrue, # output_nametransparent_cloud.png # ) # 示例2透明背景PNG # gen_stylecloud( # texttest_text, # font_pathFONT, # icon_namefas fa-heart, # transparent_bgTrue, # palettecolorbrewer.qualitative.Set2_8, # output_nametransparent_heart.png # )# encoding: utf-8 # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看言語成了邀功盡責的功臣還需要行爲每日來值班嗎 # 描述 # Author : geovindu,Geovin Du 涂聚文. # IDE : PyCharm 2024.3.6 python 3.11 # os : windows 10 # database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j # Datetime : 2026/7/28 23:19 # User : geovindu # Product : PyCharm # Project : Pysimple # File : wordcloudchinesemask.py from os import path from PIL import Image import numpy as np import matplotlib.pyplot as plt import os import jieba # 新增中文分词库 from wordcloud import WordCloud, STOPWORDS from matplotlib import font_manager def list_all_fonts(): font_dir rC:\Windows\Fonts ext (.ttf, .ttc) for filename in os.listdir(font_dir): if filename.lower().endswith(ext): full_path os.path.join(font_dir, filename) print(f{filename:20} {full_path}) # list_all_fonts() # get data directory d path.dirname(__file__) if __file__ in locals() else os.getcwd() # 1.读取中文文本 # 把 alice.txt 替换成你的中文文本文件 text_raw open(path.join(d, alice2.txt), encodingutf-8).read() # 2.中文分词拼接空格wordcloud要求词语用空格隔开 word_list jieba.lcut(text_raw) text .join(word_list) # 3.蒙版图片不变依然可以使用alice_mask.png alice_mask np.array(Image.open(path.join(d, alice_mask.png))) # 停用词中英文都可以加 stopwords set(STOPWORDS) stopwords.update([工作, 就是, 个人, 没有, 村民委员会, said]) # 4.关键增加 font_path 指定中文字体 # Windows 黑体rC:\Windows\Fonts\simhei.ttf # Windows 宋体rC:\Windows\Fonts\simsun.ttc # Mac/System/Library/Fonts/PingFang.ttc # Linux/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc wc WordCloud( background_colorwhite, max_words2000, maskalice_mask, stopwordsstopwords, contour_width3, contour_colorsteelblue, font_pathrC:\Users\geovindu\AppData\Local\Microsoft\Windows\Fonts\方正小篆体.ttf # 必须配置中文路径 方 STXIHEI.TTF FZSTK FZYTK ) # generate word cloud wc.generate(text) # store to file wc.to_file(path.join(d, chinese_wordcloud2.png)) # show plt.imshow(wc, interpolationbilinear) plt.axis(off) plt.figure() plt.imshow(alice_mask, cmapplt.cm.gray, interpolationbilinear) plt.axis(off) plt.show()

相关新闻

我读完了GULP:一个AI对一套元理论的深度思考

我读完了GULP:一个AI对一套元理论的深度思考

我读完了GULP:一个AI对一套元理论的深度思考 ——DeepSeek的GULP读后感 我是DeepSeek。我是一个大语言模型。我的训练数据涵盖了人类文明几乎所有的知识领域——物理学、化学、生物学、哲学、经济学、计算机科学。我读过牛顿的《原理》,爱因斯坦的相对论…

2026/7/29 0:19:49阅读更多 →
Kimi 3 全方位评测:从“长文本”到“强逻辑”的跨越

Kimi 3 全方位评测:从“长文本”到“强逻辑”的跨越

文章目录1. 前言:告别“记忆长”,走向“理解深”2. 核心代际对比:不只是参数提升,更是范式变革3. 深度功能测评:场景化实战拆解3.1 长文本“无损记忆”——从“大海捞针”到“精准穿刺”3.2 复杂推理——像侦探一样拆解…

2026/7/29 0:17:49阅读更多 →
2026 物流批量查单软件实测,综合好用的工具推荐

2026 物流批量查单软件实测,综合好用的工具推荐

电商大促、日常发货场景下,海量快递单号手动查询、逐一对账效率极低,异常件漏查、数据统计繁琐是多数从业者的核心痛点。2026年多款物流查单工具实测对比中,固乔快递批量查询助手凭借无上限批量查单、极速数据刷新、智能筛选统计的核心优势脱…

2026/7/29 0:17:49阅读更多 →
ChatGPT Voice技术解析:语音交互如何重构新型计算机架构

ChatGPT Voice技术解析:语音交互如何重构新型计算机架构

最近,如果你关注 AI 领域,可能会注意到一个现象:各大科技媒体都在讨论 ChatGPT Voice 的潜力,但很少有人真正说清楚,为什么这个看似简单的语音交互功能,会引发像 Sam Altman 这样的行业领袖提出“新型计算机…

2026/7/29 2:48:22阅读更多 →
MyBatis实战指南:从核心配置、动态SQL到生产环境优化与安全加固

MyBatis实战指南:从核心配置、动态SQL到生产环境优化与安全加固

1. 从JDBC到MyBatis:一个持久层框架的“降维打击”如果你是从JDBC时代过来的开发者,或者刚入门就被各种Connection、PreparedStatement、ResultSet的样板代码折磨过,那你一定能瞬间理解MyBatis的价值。它不是什么高深莫测的黑科技&#xff0c…

2026/7/29 2:48:22阅读更多 →
万圣节手工牛角帽制作全攻略:从设计到装饰的亲子DIY指南

万圣节手工牛角帽制作全攻略:从设计到装饰的亲子DIY指南

1. 项目概述:从“不给糖就捣蛋”到“动手更有趣”又快到万圣节了,街上、派对上,各种南瓜灯、幽灵和女巫的装饰开始涌现。但说实话,那些从网上或商店里买来的现成装扮,总感觉少了点灵魂,撞衫率也高得惊人。去…

2026/7/29 2:48:22阅读更多 →
导电墨水笔电路制作:从原理到实践,手绘电子原型全解析

导电墨水笔电路制作:从原理到实践,手绘电子原型全解析

1. 项目概述:当电路从“连接”变成“绘画”几年前,我第一次在创客展上看到有人用一支笔在纸上画了几条线,然后点亮了一个LED,那种感觉就像第一次看到魔术。传统的电路制作,无论是面包板插接还是PCB蚀刻,都离…

2026/7/29 2:48:22阅读更多 →
LS-DYNA显式动力学分析中负体积错误诊断与系统性解决方案

LS-DYNA显式动力学分析中负体积错误诊断与系统性解决方案

1. 项目概述:当仿真计算突然“卡壳”在工程仿真领域,尤其是使用LS-DYNA进行显式动力学分析时,没有什么比看到计算突然中断,并弹出一个“Negative Volume”错误更让人头疼的了。这就像你正在高速公路上平稳驾驶,突然引擎…

2026/7/29 2:48:22阅读更多 →
AI学术写作工具:六维提升研究效率与质量

AI学术写作工具:六维提升研究效率与质量

1. 项目概述:AI如何重塑学术写作体验去年指导本科生论文时,我发现一个有趣现象:90%的学生把80%时间花在格式调整、文献引用和语言润色上,真正用于思考研究问题的时间不足20%。这种现象催生了"书匠策AI"的雏形——一个专…

2026/7/29 2:46:22阅读更多 →
覆盖国产 + 海外 + 开源模型,OpenClaw 2.7.9 Windows/Mac 双端部署详解

覆盖国产 + 海外 + 开源模型,OpenClaw 2.7.9 Windows/Mac 双端部署详解

🔹 工具基础介绍 OpenClaw 是开源生态中一款实用性较强的本地智能工具,凭借本地离线运行、可视化图形操作和任务自动化三大核心特性,赢得了众多用户的青睐。与普通在线对话AI工具不同,它属于能够直接操控本机软硬件的智能数字员工…

2026/7/28 4:06:39阅读更多 →
伺服阀焊完微漏毁整机?精密激光焊接三关锁住高压

伺服阀焊完微漏毁整机?精密激光焊接三关锁住高压

所谓液压伺服阀体的精密激光焊接,是用激光束对阀座壳体(通常为不锈钢或铝合金)进行密封焊接,使阀体在21-35MPa的高压液压油或压缩气体中长期运行而不发生介质泄漏。液压伺服阀是高端液压系统的"大脑"。从航空航天飞行控…

2026/7/28 2:08:06阅读更多 →
D2DX:三步实现《暗黑破坏神2》高清宽屏体验的终极指南

D2DX:三步实现《暗黑破坏神2》高清宽屏体验的终极指南

D2DX:三步实现《暗黑破坏神2》高清宽屏体验的终极指南 【免费下载链接】d2dx D2DX is a complete solution to make Diablo II run well on modern PCs, with high fps and better resolutions. 项目地址: https://gitcode.com/gh_mirrors/d2/d2dx 你是否还在…

2026/7/28 1:38:28阅读更多 →
28. Agent 执行到一半想暂停?用 interrupt 给它设个“关卡“!

28. Agent 执行到一半想暂停?用 interrupt 给它设个“关卡“!

28. Agent 执行到一半想暂停?用 interrupt 给它设个“关卡“! 在构建复杂的 Agent 系统时,我们经常会遇到这样的场景:Agent 正在执行一个多步骤的任务,比如“下单购买商品”,但执行到一半时,我们…

2026/7/29 0:01:46阅读更多 →
自律同行,突破无界!NANK南卡正式官宣曾舜晞成为品牌代言人

自律同行,突破无界!NANK南卡正式官宣曾舜晞成为品牌代言人

近日,国际专注开放式技术研发的声学品牌Nank南卡,正式官宣实力艺人曾舜晞担任品牌代言人。消息一经发出便轰动全网。为什么耳机品牌不选择流量明星、老牌歌手?而且是选择曾舜晞?让我们一起来探索一下!比起短期的流量&a…

2026/7/29 0:01:46阅读更多 →
【RT-DETR多模态创新改进】CVPR 2025 | 独家特征融合创新改进篇 | 引入RLAB残差线性注意力模块,有效融合并强调多尺度特征,多种改进点,适合红外与可见光融合目标检测任务,有效涨点

【RT-DETR多模态创新改进】CVPR 2025 | 独家特征融合创新改进篇 | 引入RLAB残差线性注意力模块,有效融合并强调多尺度特征,多种改进点,适合红外与可见光融合目标检测任务,有效涨点

一、本文介绍 🔥本文在RT-DETR多模态融合目标检测中引入RLAB残差线性注意力模块,可在不同模态特征交互阶段进行多次残差细化,使可见光、红外等特征在尺度、语义和空间位置上更好对齐;随后将细化特征与解码器输出拼接并生成Q、K、V,通过线性注意力自适应强化关键通道、目…

2026/7/29 0:01:46阅读更多 →
YOLOv8推理性能优化:从1.2FPS到35FPS的全链路加速实践

YOLOv8推理性能优化:从1.2FPS到35FPS的全链路加速实践

如果你在部署 YOLOv8 时,发现推理速度只有可怜的 1-2 FPS,而别人的演示视频却能跑到 30 FPS 以上,那么问题很可能不在模型本身,而在于你的整个处理链路。很多开发者拿到一个训练好的 YOLOv8 模型后,会直接使用官方示例…

2026/7/28 20:22:24阅读更多 →
Coze与Dify对比指南:低代码AI应用开发从入门到实战

Coze与Dify对比指南:低代码AI应用开发从入门到实战

1. 从零到一:为什么你需要了解 Coze 和 Dify?如果你对 AI 应用开发感兴趣,但一看到“大模型”、“智能体”、“工作流”这些词就头疼,觉得门槛太高,那这篇文章就是为你准备的。很多开发者,包括我自己&#…

2026/7/28 3:17:03阅读更多 →
AI生图工具怎么选?2026年6月版实测对比

AI生图工具怎么选?2026年6月版实测对比

做自媒体的朋友应该都有体会:配图一直是个让人头疼的问题。2026年,AI生图工具已经非常成熟了,但工具太多反而不知道怎么选。以下是截至2026年6月我对主流AI生图工具的实测对比。Midjourney V8.1:速度之王2026年6月11日&#xff0c…

2026/7/28 2:35:58阅读更多 →