Python生成WordCloud词云保存至桌面失败:'WordCloud' object has no attribute 'save'错误求助
Hey there! The issue here is pretty straightforward: the WordCloud object from the wordcloud library doesn't have a save() method — you’re using the wrong method name. Let’s fix this with two simple, reliable solutions:
Solution 1: Use WordCloud's built-in to_file() method
This is the most direct approach, as to_file() is the official method designed to save your generated word cloud directly to a file. Just swap out your img.save() line with img.to_file():
import pandas as pd from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt df = pd.read_excel("C:/Users/06HAK003/Desktop/Folders/programming/Excel files/DATAFRAME.xlsx") text = " ".join(cat.split()[0] for cat in df.Car) def plot_cloud(wordcloud): # Set figure size plt.figure(figsize=(15, 5)) # Display image plt.imshow(wordcloud) # No axis details plt.axis("off"); # Generate word cloud img = WordCloud(width= 3000, height = 2000, background_color='black', colormap='plasma', collocations=False, stopwords = STOPWORDS).generate(text) plot_cloud(img) # Replace save() with to_file() img.to_file('C:/Users/06HAK003/Desktop/cloud.png')
Solution 2: Save via Matplotlib (since you’re already using it to plot)
If you want to save the exact plot you’re displaying (including any figure size adjustments you’ve made), use plt.savefig() right after calling your plot_cloud function. This ensures you capture the exact visual you see:
import pandas as pd from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt df = pd.read_excel("C:/Users/06HAK003/Desktop/Folders/programming/Excel files/DATAFRAME.xlsx") text = " ".join(cat.split()[0] for cat in df.Car) def plot_cloud(wordcloud): # Set figure size plt.figure(figsize=(15, 5)) # Display image plt.imshow(wordcloud) # No axis details plt.axis("off"); # Generate word cloud img = WordCloud(width= 3000, height = 2000, background_color='black', colormap='plasma', collocations=False, stopwords = STOPWORDS).generate(text) plot_cloud(img) # Save the Matplotlib figure plt.savefig('C:/Users/06HAK003/Desktop/cloud.png', dpi=300, bbox_inches='tight')
dpi=300guarantees a high-resolution, crisp imagebbox_inches='tight'prevents any edges of your word cloud from being cut off
Either solution will successfully save your word cloud to the desktop. Give them a go!
内容的提问来源于stack exchange,提问作者Harsimrat

