Wordcloud包帮助我们通过可视化来了解文本内容中单词的频率。

要实现这一点,我们首先需要安装一些包,如pandas、matplotlib和Wordcloud。

让我们看看每个包的安装步骤:

安装Pandas

Pandas是在Jupyter Notebook中执行数据分析和可视化的强大工具。可以使用以下方式将其导入我们的源代码中:

import pandas as pd 

"pd"是别名的过程,可以使用它创建数据框,并且它可以提高代码的可读性。

可以使用两种方法安装Pandas:

1. 使用命令提示符

首先,让我们看看如何使用命令提示符来实现我们的目标。

  1. 打开命令提示符
  2. 输入以下命令:

    pip install pandas
  3. 单击"Enter",包将开始下载到我们的系统中。

相同的命令可以在Linux终端中使用以安装Pandas。

2. 使用Anaconda导航器

在系统中安装Pandas的第二种方法是使用Anaconda导航器。

  1. 打开Anaconda导航器。
  2. 单击"环境"选项卡,然后单击创建选项以在系统中安装Pandas。
  3. 单击Pandas环境的"创建"按钮。
  4. 在包列表中,选择"全部"以获取筛选器。
  5. 转到搜索框,搜索"Pandas"并选择"Pandas包"。
  6. 右键单击复选框,然后选择"标记为特定版本安装"。
  7. 选择要安装的版本,然后单击"应用"按钮以安装包。

258-1.png

安装Matplotlib

Matplotlib是一个庞大且有趣的库,适用于那些热衷于从数据中推断结果的人。它包括散点图、直方图、箱线图等等,这使我们更容易理解数据。

可以按照以下步骤安装Matplotlib:

  • 使用命令提示符

可以使用以下命令在系统中安装Matplotlib:

pip install matplotlib  
  • 使用Anaconda

可以使用Anaconda命令提示符通过输入以下命令在系统中安装Matplotlib:

conda install matplotlib   

258-2.png

验证安装

我们可以验证Matplotlib是否已成功安装在系统中,方法是在终端中键入以下程序:

pythonCopy codeimport matplotlib
matplotlib.__version__

安装Wordcloud

如前所述,Wordcloud包通过可视化方式向我们展示文本中出现最频繁的单词。

让我们看看安装的步骤:

可以按照以下步骤安装WordCloud:

  • 使用命令提示符

可以使用以下命令在系统中安装Wordcloud:

import matplotlib  
matplotlib.__version__ 
  • 使用Anaconda

可以使用Anaconda命令提示符通过输入以下命令在系统中安装Wordcloud:

pip install wordcloud

现在让我们看看如何在Python中使用Wordcloud的简单程序。

我们从网站中摘取了这段文本并保存为sunflowers1.txt文件。

sunflowers1.txt

"Sunflowers are heliotropic, which means that they turn their flowers to follow the movement of the Sun across the sky east to west, and then returns at night to face the east, ready again for the morning sun. Heliotropism happens during the earlier stages before the flower grows heavy with seeds.  
There are tons of varieties of sunflowers available today, so there's bound to be one that fits your garden. Choose between those with branching stems or single stems, those that produce ample pollen for pollinators or are pollen-free (best for bouquets), those that stay small or tower above the rest of the garden, or those that produce edible seeds! "  

代码实现

import re  
import matplotlib.pyplot as plt  
from wordcloud import WordCloud, STOPWORDS  
text = open("/content/sunflowers1.txt", "r").read()  
# Clean text  
text = re.sub(r'==.*?==+', '', text)  
text = text.replace('\n', '')  
# Define a function to plot word cloud  
def plot_cloud(wordcloud):  
    # Set figure size  
    plt.figure(figsize=(40, 30))  
    # Display image  
    plt.imshow(wordcloud)   
    # No axis details  
    plt.axis("off")  
# Generate word cloud  
wordcloud = WordCloud(width = 3000, height = 2000, random_state=1, background_color='salmon', colormap='Pastel1', collocations=False, stopwords = STOPWORDS).generate(text)  
plot_cloud(wordcloud)  

输出:

258-3.png

标签: Tkinter教程, Tkinter安装, Tkinter库, Tkinter入门, Tkinter学习, Tkinter入门教程, Tkinter, Tkinter进阶, Tkinter指南, Tkinter学习指南, Tkinter进阶教程, Tkinter编程