在 Python 中,python,nltk,word-cloud"/>

首页 > 解决方案 > 处理在 Python 中

问题描述

我正在使用 Python 中的“wordcloud”包并尝试获取我自己的三语(英语、法语和德语)停用词列表。

这个“EN_FR_DE”停用词列表与我 PC 上的标准 NLTK 停用词列表一起存储在 NLTK 数据文件夹中,因为我也在其他上下文中使用它。我现在想导入这个自定义停用词列表,将其转换为字符串并在“wordcloud”中使用。我使用“字符串”来转换列表。但是,当我检查它的“类型”时,输出仍然是:

<class 'nltk.corpus.reader.wordlist.WordListCorpusReader'>

当然,“wordcloud”不接受此列表并忽略所有停用词(参见下面链接的图表)。

我什至不知道这是它自己的一个类,我找不到如何处理这种特殊类型的类的说明。将其转换为字符串的正确方法是什么?

我构建 wordcloud 的完整脚本是:

# Generate word cloud from publication titles in English, French and German

from wordcloud import WordCloud
import matplotlib.pyplot as plt 
import string
import nltk
from nltk.corpus import stopwords

infile=("C:\\Users\\mobarget\\Google Drive\\ACADEMIA\\Metadata_PhD\\BritishRiots_TopicModel\\British_riots_text.txt")  

# define stopwords and convert them to string

stopwords_multiling=' '.join(stopwords.words('en_fr_de'))
print(stopwords_multiling[:50])
print(type(stopwords))

# read and pre-process data

with open(infile, 'r', encoding='utf-8') as f: # open file
    data1=f.read() # read content of file as string
    data2=data1.translate(str.maketrans('', '', string.punctuation)).lower() # remove punctuation
    data3=' '.join(data2.split()) # remove additional whitespace from text

# define word cloud layout

wordcloud = WordCloud(width = 800, height = 800, 
                background_color ='white', 
                stopwords = stopwords_multiling, 
                min_font_size = 10).generate(data3) 

# plot the WordCloud image   

plt.figure(figsize = (8, 8), facecolor = None) 
plt.imshow(wordcloud, interpolation="bilinear") 
plt.axis("off") 
plt.tight_layout(pad = 0) 

plt.show() 

这是输出:

i me my myself we our ours ourselves you you're yo
<class 'nltk.corpus.reader.wordlist.WordListCorpusReader'>

图形图像

标签: pythonnltkword-cloud

解决方案


推荐阅读