* * * ### **步骤 1:安装依赖包** ```bash # 核心依赖 pip install wordcloud jieba matplotlib pymysql ``` * * * ### **步骤 2:完整代码实现** ```python import mysql.connector from wordcloud import WordCloud import jieba import matplotlib.pyplot as plt from collections import Counter # ========== 配置部分 ========== DB_CONFIG = { "host": "localhost", "user": "your_username", "password": "your_password", "database": "wnacg" } FONT_PATH = 'SimHei.ttf' # 中文字体文件路径(需自行下载) STOPWORDS_FILE = 'chinese_stopwords.txt' # 停用词表路径 OUTPUT_IMAGE = 'wordcloud.png' # 输出图片路径 # ============================= def fetch_text_data(): """从数据库获取标题和标签数据""" conn = mysql.connector.connect(**DB_CONFIG) cursor = conn.cursor() cursor.execute("SELECT title, tags FROM cartoon") results = cursor.fetchall() cursor.close() conn.close() # 合并标题和标签 return [' '.join([title, tags]) for title, tags in results] def process_text(texts): """文本处理流程""" # 加载停用词 with open(STOPWORDS_FILE, 'r', encoding='utf-8') as f: stopwords = set(f.read().splitlines()) # 中文分词处理 words = [] for text in texts: seg_list = jieba.cut(text) words.extend([word.strip() for word in seg_list if word.strip() and word not in stopwords and len(word) > 1]) # 过滤单字 return words def generate_wordcloud(words): """生成词云""" word_freq = Counter(words) wc = WordCloud( font_path=FONT_PATH, width=1600, height=1200, background_color='white', max_words=200, colormap='viridis' ).generate_from_frequencies(word_freq) plt.figure(figsize=(20, 15)) plt.imshow(wc, interpolation='bilinear') plt.axis("off") plt.savefig(OUTPUT_IMAGE, bbox_inches='tight') plt.show() if __name__ == "__main__": # 执行流程 texts = fetch_text_data() words = process_text(texts) generate_wordcloud(words) print(f"词云已生成至:{OUTPUT_IMAGE}") ``` * * * ### **步骤 3:准备工作** 1. **中文字体文件**: - 下载微软雅黑字体 [SimHei.ttf](https://www.wfonts.com/font/simhei) - 或使用系统已有中文字体(如`C:/Windows/Fonts/msyh.ttc`) 2. **停用词表**: - 创建 `chinese_stopwords.txt` 文件,内容示例: ```text 的 是 在 了 和 ... ``` - 或直接使用[哈工大停用词表](https://github.com/goto456/stopwords/raw/master/cn_stopwords.txt) * * * ### **关键参数说明** | 参数 | 作用 | 推荐值 | | --- | --- | --- | | `max_words` | 显示最大词汇量 | 100-300 | | `width/height` | 图片分辨率 | 根据显示需求调整 | | `colormap` | 颜色主题 | viridis, plasma, tab20等 | | `background_color` | 背景颜色 | "white" 或 "#FFFFFF" | | `collocations` | 是否合并词组(中文建议关闭) | False(需修改代码) | * * * ### **扩展功能建议** 1. **自定义形状**: ```python from PIL import Image mask = np.array(Image.open("shape.png")) # 使用图片形状模板 WordCloud(mask=mask, ...) ``` 2. **词频输出**: ```python # 在 generate_wordcloud 函数后添加 with open('word_freq.csv', 'w') as f: for word, freq in word_freq.most_common(100): f.write(f"{word},{freq}\n") ``` 3. **交互式可视化**: ```bash pip install pyecharts ``` 使用 [pyecharts](https://pyecharts.org/) 生成可交互的词云网页 * * * 通过这个方案,可以快速实现基于数据库文本数据的可视化分析。如果需要处理超大文本量(>10万条),需要添加分页查询和进度显示功能。 以下是使用 `pymysql` 替代 `mysql-connector-python` 的完整改造方案: * * * ### **改造步骤说明** #### 1\. 安装依赖变更 ```bash # 卸载旧库(如果已安装) pip uninstall mysql-connector-python # 安装新库 pip install pymysql ``` #### 2\. 代码修改对比 | 原代码 (mysql-connector) | 新代码 (pymysql) | | --- | --- | | `import mysql.connector` | `import pymysql` | | `conn = mysql.connector.connect(...)` | `conn = pymysql.connect(...)` | * * * ### **完整改造后的词云代码** ```python import pymysql # 关键修改点 from wordcloud import WordCloud import jieba import matplotlib.pyplot as plt from collections import Counter # ========== 配置部分 ========== DB_CONFIG = { "host": "localhost", "user": "your_username", "password": "your_password", "database": "wnacg", "charset": "utf8mb4", # 新增推荐编码配置 "cursorclass": pymysql.cursors.DictCursor # 可选:返回字典格式数据 } FONT_PATH = 'SimHei.ttf' STOPWORDS_FILE = 'chinese_stopwords.txt' OUTPUT_IMAGE = 'wordcloud_pymysql.png' # ============================= def fetch_text_data(): """从数据库获取数据(使用pymysql)""" conn = pymysql.connect(**DB_CONFIG) # 修改连接方式 try: with conn.cursor() as cursor: # 自动管理游标 cursor.execute("SELECT title, tags FROM cartoon") results = cursor.fetchall() # 字典模式处理(如果配置了cursorclass=DictCursor) return [' '.join([row['title'], row['tags']]) for row in results] # 元组模式(默认): # return [' '.join([title, tags]) for title, tags in results] finally: conn.close() # 确保连接关闭 # 以下 processing_text 和 generate_wordcloud 函数保持不变 # ... (与之前代码完全相同) if __name__ == "__main__": texts = fetch_text_data() words = process_text(texts) generate_wordcloud(words) ``` * * * ### **关键修改点详解** 1. **连接参数增强**: - 新增 `charset="utf8mb4"` 支持完整的Unicode字符 - 可选 `cursorclass=pymysql.cursors.DictCursor` 使查询结果返回字典格式 2. **连接关闭优化**: - 使用 `try/finally` 确保数据库连接始终关闭 - `with conn.cursor()` 上下文管理器自动释放游标资源 3. **结果集处理**: - 默认返回元组数据:`row[0]` 对应第一个字段 - 字典模式需明确配置:`row['title']` 按字段名访问 * * * ### **可能遇到的问题及解决方案** | 问题现象 | 原因 | 解决方案 | | --- | --- | --- | | `ImportError: No module named 'pymysql'` | 未安装库 | `pip install pymysql` | | `Can't connect to MySQL server` | 权限/网络问题 | 检查MySQL用户远程连接权限 | | `Incorrect string value` | 编码问题 | 确保配置 `charset="utf8mb4"` | | `SSLError` | SSL连接问题 | 添加 `ssl={"ssl": {"fake_flag": True}}` 参数 | * * * ### **性能对比建议** | 场景 | 推荐驱动 | | --- | --- | | 需要SSL加密连接 | `mysql-connector` | | 高频短查询 | `pymysql` | | 大量二进制数据处理 | `mysqlclient` (C扩展) | 如果后续需要更高性能,可以进一步改用 `mysqlclient`(只需修改为 `import MySQLdb` 其他语法与pymysql兼容)。 [SexWord.py](../../_resources/SexWord.py)