You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

垃圾邮件检测:垃圾邮件与正常邮件关键词词云可视化故障求助

Hey there! Let's troubleshoot why your spam word cloud isn't rendering correctly. I’ve spotted a couple of likely issues right away, so let’s work through them step by step.

Fixing the Spam Word Cloud Generation Issue

First: The Core Data Mismatch Problem

Looking at your data processing code, you replaced spam with the string value "1", but when filtering for spam messages, you’re checking against the integer 1. This mismatch means your code is returning an empty set of messages—so there’s nothing to generate a word cloud from!

You can fix this in two easy ways:

Option 1: Adjust the Filter to Match String Values

Update your spam message filter to target the string "1" instead of the integer 1:

spam_words = ' '.join(list(data[data['label'] == "1"]['message']))

Option 2: Convert Labels to Integers During Data Cleaning

Modify your data replacement step to use integers directly, so your filter works as-is:

data = data.replace({"spam":1,"ham":0})  # Use integers instead of strings

Second: Complete the Word Cloud Generation Code

If your existing code cuts off after joining the spam words, here’s a full, runnable example that includes rendering the word cloud (plus a bonus ham word cloud for comparison):

import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
import pandas as pd

# Data cleaning (using Option 2 above)
data = pd.read_csv("spam.csv", encoding='latin-1')
data = data.rename(columns={"v1":"label", "v2":"message"})
data = data.replace({"spam":1, "ham":0})

# Generate Spam Word Cloud
spam_words = ' '.join(list(data[data['label'] == 1]['message']))
# Add STOPWORDS to filter out generic, meaningless terms like "the" or "you"
spam_wordcloud = WordCloud(
    width=800, 
    height=500, 
    background_color='white', 
    max_words=100,
    stopwords=STOPWORDS
).generate(spam_words)

# Visualize Spam Word Cloud
plt.figure(figsize=(10,6))
plt.imshow(spam_wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('Spam Message Word Cloud')
plt.show()

# Optional: Generate Ham Word Cloud for Comparison
ham_words = ' '.join(list(data[data['label'] == 0]['message']))
ham_wordcloud = WordCloud(
    width=800, 
    height=500, 
    background_color='white', 
    max_words=100,
    stopwords=STOPWORDS
).generate(ham_words)

plt.figure(figsize=(10,6))
plt.imshow(ham_wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('Ham (Legitimate) Message Word Cloud')
plt.show()

Quick Pre-Check

Make sure you have all required libraries installed. If not, run this command first:

pip install pandas matplotlib wordcloud

内容的提问来源于stack exchange,提问作者Prashant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:45:21