SexWord.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import pymysql
  2. from wordcloud import WordCloud
  3. import matplotlib.pyplot as plt
  4. import jieba
  5. import os
  6. # 数据库配置
  7. db_config = {
  8. "host": "localhost",
  9. "port": 3306,
  10. "user": "kekezack",
  11. "password": "daofengyizhi@66",
  12. "database": "wnacg",
  13. }
  14. try:
  15. # 连接数据库
  16. conn = pymysql.connect(**db_config)
  17. cursor = conn.cursor()
  18. # 查询标题和标签数据
  19. query = "SELECT title, tag_list FROM cartoon;"
  20. cursor.execute(query)
  21. results = cursor.fetchall()
  22. # 提取并合并文本数据
  23. text_data = []
  24. for row in results:
  25. title = row[0]
  26. if title:
  27. text_data.append(title)
  28. tags = row[1]
  29. if tags:
  30. text_data.extend(tags.replace("[", "").replace("]", "").split(","))
  31. all_text = ",".join(text_data)
  32. except pymysql.MySQLError as e:
  33. print(f"Error: {e}")
  34. finally:
  35. cursor.close()
  36. conn.close()
  37. # 分词和处理
  38. stopwords = {"的", "是", "我", "在"}
  39. word_list = []
  40. for word in jieba.cut(all_text):
  41. if len(word) > 1 and word not in stopwords:
  42. word_list.append(word)
  43. wordcloud_data = " ".join(word_list)
  44. # 生成词云
  45. wc = WordCloud(
  46. font_path="simhei.ttf", width=800, height=600, background_color="white"
  47. ).generate(wordcloud_data)
  48. plt.figure(figsize=(12, 8))
  49. plt.imshow(wc)
  50. plt.axis("off")
  51. # 保存词云图片
  52. wc.to_file(os.path.join(os.getcwd(), "sexword.png"))
  53. # 显示词云图片
  54. # plt.show()