| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- import pymysql
- from wordcloud import WordCloud
- import matplotlib.pyplot as plt
- import jieba
- import os
- # 数据库配置
- db_config = {
- "host": "localhost",
- "port": 3306,
- "user": "kekezack",
- "password": "daofengyizhi@66",
- "database": "wnacg",
- }
- try:
- # 连接数据库
- conn = pymysql.connect(**db_config)
- cursor = conn.cursor()
- # 查询标题和标签数据
- query = "SELECT title, tag_list FROM cartoon;"
- cursor.execute(query)
- results = cursor.fetchall()
- # 提取并合并文本数据
- text_data = []
- for row in results:
- title = row[0]
- if title:
- text_data.append(title)
- tags = row[1]
- if tags:
- text_data.extend(tags.replace("[", "").replace("]", "").split(","))
- all_text = ",".join(text_data)
- except pymysql.MySQLError as e:
- print(f"Error: {e}")
- finally:
- cursor.close()
- conn.close()
- # 分词和处理
- stopwords = {"的", "是", "我", "在"}
- word_list = []
- for word in jieba.cut(all_text):
- if len(word) > 1 and word not in stopwords:
- word_list.append(word)
- wordcloud_data = " ".join(word_list)
- # 生成词云
- wc = WordCloud(
- font_path="simhei.ttf", width=800, height=600, background_color="white"
- ).generate(wordcloud_data)
- plt.figure(figsize=(12, 8))
- plt.imshow(wc)
- plt.axis("off")
- # 保存词云图片
- wc.to_file(os.path.join(os.getcwd(), "sexword.png"))
- # 显示词云图片
- # plt.show()
|