WordCloud 包幫助我們使用可視化了解文本內容中單詞的出現頻率。
為了實現這一點,我們需要首先安裝一些包,比如 pandas、matplotlib 和 Wordcloud。
讓我們來看看每個的安裝步驟-
Pandas 裝置
Pandas 是在 Jupyter 筆記本中實現數據分析和可視化的一個很好的工具。它可以通過以下方式導入到我們的源代碼中-
import pandas as pd
pd 指的是混疊過程,藉助這一過程可以創建數據幀,並使代碼的可讀性更容易。
Pandas 可以通過兩種方式安裝-
1.使用命令提示符
首先,讓我們看看如何使用命令提示符來實現我們的目標。
- 打開命令提示符
- 鍵入給定的命令-
皮普安裝 PandasT4】 - 單擊「輸入」後,軟體包將開始在我們的系統中下載。
同樣的命令可以在終端的 Linux 中使用,在我們的系統中安裝 Pandas。
2.使用 Python 導航器
在我們的系統中安裝 Pandas 的第二種方法是使用 Anaconda Navigator
- 打開 Python 導航器。
- 單擊「環境」選項卡,轉到創建選項,在您的系統中設置 Pandas。
- 點擊創建 Pandas 環境按鈕。
- 在包列表中,選擇「全部」以獲取過濾器。
- 去搜索欄找「Pandas」,選擇「Pandas 套餐」。
- 右鍵單擊複選框,然後轉到「標記特定版本安裝」。
- 選擇我們要安裝的版本,然後單擊「應用」按鈕安裝軟體包。
安裝 Matplotlib
Matplotlib 是一個巨大而有趣的庫,適合熱衷於從數據中推斷結果的人,它有散點圖、直方圖、箱線圖等等,這讓我們很容易理解。
Matplotlib 可以按照給定的步驟安裝-
- 使用命令提示符
Matplotlib 可以通過使用命令提示符中給定的命令安裝在我們的系統中
pip install matplotlib
- 使用 Python
我們可以通過在 Anaconda 提示符下鍵入以下命令來使用 Anaconda 安裝 matplotlib
conda install matplotlib
驗證安裝
我們可以通過在終端鍵入給定的程序來驗證 matplotlib 是否已經成功安裝在我們的系統中-
import matplotlib
matplotlib.__version__
Wordcloud 的安裝
如前所述,它讓我們在視覺的幫助下了解文本中出現最多的單詞。
讓我們看看安裝的步驟-
可以按照給定的步驟安裝 WordCloud
- 使用命令提示符
通過使用命令提示符中給定的命令,可以在我們的系統中安裝 WordCloud。
pip install wordcloud
- 使用 Python
我們可以通過在 Anaconda 提示符中鍵入以下命令來使用 Anaconda 安裝 wordcloud。
conda install -c conda-forge wordcloud
現在讓我們看看這個簡單的程序,它展示了如何在 Python 中使用單詞雲。
我們從一個網站上獲取了這段文字,並保存為 sunflowers1.txt 文件。
向日葵 1.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)
輸出:
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/253498.html