簡體   English   中英

如何在不刪除文本中的標點符號的情況下創建詞雲?

[英]How to create a wordcloud without removing the punctuations in the text?

我正在嘗試在 python 中創建詞雲。 我的目標是讓 csv 文件中的單詞按原樣顯示,不刪除任何標點符號。 我嘗試了幾種方法,但我不確定該怎么做。 目前,我使用的代碼刪除了標點符號。 如何在不刪除標點符號的情況下創建 wordcloud。

我擁有的數據是這樣的 csv 格式的單列數據(標題是 CONTENT3)。

CONTENT3
NumVeh:SV
Driver_age:25-44
Rd_desc:straightflat
Weather:clear
NumVeh:SV
Weather:clear

我使用的代碼如下:

import pandas as pd
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS


comment_words = ''
stopwords = set(STOPWORDS)
 
# iterate through the csv file
for val in df1.CONTENT3:
     
    # typecaste each val to string
    val = str(val)
 
    # split the value
    tokens = val
    tokens = val.split()
     
    # Converts each token into lowercase
    for i in range(len(tokens)):
        tokens[i] = tokens[i].lower()
     
    comment_words += " ".join(tokens)+" "
 
wordcloud = WordCloud(width = 2000, height = 2000,
                random_state=1, background_color='white', colormap='Set2', collocations=True,
                stopwords = stopwords,
                min_font_size = 10).generate(comment_words)
 
# plot the WordCloud image                      
plt.figure(figsize = (8, 8), facecolor = None)
plt.imshow(wordcloud)
plt.axis("off")
plt.tight_layout(pad = 0)
 
plt.show()

結果如下。 雖然出現下划線,但冒號和其他標點符號會自動刪除。

在此處輸入圖像描述

import re
import pandas as pd
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS


comment_words = ''
stopwords = set(STOPWORDS)
 
# iterate through the csv file
for val in df1.CONTENT3:
     
    # typecaste each val to string
    val = str(val)
 
    # split the value on any non-word character
    tokens = re.split(r'[^\w]+', val)
     
    # Converts each token into lowercase
    for i in range(len(tokens)):
        tokens[i] = tokens[i].lower()
     
    comment_words += " ".join(tokens)+" "
 
wordcloud = WordCloud(width = 2000, height = 2000,
                random_state=1, background_color='white', colormap='Set2', collocations=False,
                stopwords = stopwords,
                min_font_size = 10).generate(comment_words)
 
# plot the WordCloud image                      
plt.figure(figsize = (8, 8), facecolor = None)
plt.imshow(wordcloud)
plt.axis("off")
plt.tight_layout(pad = 0)
 
plt.show()
  1. 您可以在匹配任何非單詞字符(例如 [^\w]+)的正則表達式上拆分值,而不是在空格上拆分值。 這將允許您保留標點符號。

  2. 您還可以將搭配參數作為 False 傳遞給 WordCloud 構造函數。 這將防止詞雲將詞組合在一起,這可能會刪除標點符號。

我找到了解決這個問題的方法。 我使用單詞及其頻率創建了一本字典。 然后,我使用 'generate_from_frequencies' 方法繪制了 wordcloud。 wordcloud 是根據需要用標點符號創建的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM