使用Python绘制樱花摘要及关键词
时间: 2023-10-09 13:12:06 浏览: 186
要使用Python绘制樱花摘要及关键词,可以使用Python中的数据可视化库matplotlib和词云生成库wordcloud。以下是一个简单的示例代码:
```python
import matplotlib.pyplot as plt
from wordcloud import WordCloud
# 读取文本
with open('cherry_blossom.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 分词、去除停用词
stop_words = set(stopwords.words('english'))
words = [word.lower() for word in nltk.word_tokenize(text) if word.lower() not in stop_words]
# 提取关键词
r = Rake()
r.extract_keywords_from_text(text)
keywords = r.get_ranked_phrases()
# 计算词频
freq_dist = nltk.FreqDist(words)
# 绘制摘要
plt.figure(figsize=(8, 6))
plt.title('Cherry Blossom Summary')
plt.bar([word for word, frequency in freq_dist.most_common(10)], [frequency for word, frequency in freq_dist.most_common(10)])
plt.xticks(rotation=45)
plt.xlabel('Words')
plt.ylabel('Frequency')
plt.show()
# 绘制关键词词云
wordcloud = WordCloud(width=800, height=800, background_color='white', colormap='Spectral').generate(' '.join(keywords))
plt.figure(figsize=(8, 6))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
```
这段代码会读取名为`cherry_blossom.txt`的文本文件,分词、去除停用词,提取关键词,并计算词频。然后,使用matplotlib绘制摘要,绘制出现频率最高的前10个词的柱状图。同时,使用wordcloud绘制关键词词云,显示RAKE提取的前10个关键词。
请注意,这段代码也是一个简单示例,实际情况可能会更加复杂。例如,可以对词云进行更多的定制,如设置颜色、形状等。
阅读全文
相关推荐












