从列表列表中删除停止字

2024-04-29 05:20:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何从如下列表中删除特定单词,包括stopwords:

my_list=[[],
 [],
 ['A'],
 ['SB'],
 [],
 ['NMR'],
 [],
 ['ISSN'],
 [],
 [],
 [],
 ['OF', 'USA'],
 [],
 ['THE'],
 ['HOME'],
 [],
 [],
 ['STAR'],
 []]

如果是字符串列表,我会应用如下内容:

from collections import Counter
stop_words = stopwords.words('english')
text = ' '.join([word for word in my_list if word not in stop_words])

我需要在最后画出这样的图:

counts= Counter(chain.from_iterable(my_list))
plt.bar(*zip(*counts.most_common(20)))
plt.show()

预期绘制的列表:

my_list=[[],
 [],
 ['SB'],
 [],
 ['NMR'],
 [],
 ['ISSN'],
 [],
 [],
 [],
 ['USA'],
 [],
 ['HOME'],
 [],
 [],
 ['STAR'],
 []]

Tags: fromhome列表mycounterlistwordsb
1条回答
网友
1楼 · 发布于 2024-04-29 05:20:00

循环通过my_words,将每个嵌套列表替换为已删除停止词的列表。您可以使用“设置差异”删除单词

stop_words = stopwords.words('english')
my_list = [list(set(sublist).difference(stop_words)) for sublist in my_list]

不敏感地进行比较会变得更复杂一些,因为您不能使用内置的set-difference方法

my_list = [[word for word in sublist if word.lower() not in stop_words] for sublist in my_list]

相关问题 更多 >