垃圾邮件检测:垃圾邮件与正常邮件关键词词云可视化故障求助
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.
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

