如何解决停止词删除代码不起作用,返回相同的字符串
我想从一串句子中删除停用词,但是我的打印功能会返回包含所有停用词的确切字符串。这是我使用的代码,其中digest
是我从群聊中解析的句子字符串。
chat_map['Phillips Allen']
此代码返回该代码;
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
stop_words = set(stopwords.words("english"))
filtered_sentences_phillip = []
for w in chat_map['Phillip Allen']:
if w not in stop_words:
filtered_sentences_phillip.append(w)
print(filtered_sentences_phillip)
你知道怎么回事吗?
解决方法
问题的根源是,在将每个单词与停用词列表进行比较之前,您没有将句子拆分为单词。
使用str.split()
函数。
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
stop_words = set(stopwords.words("english"))
filtered_sentences_phillip = []
for w in chat_map['Phillip Allen'].split():
if w not in stop_words:
filtered_sentences_phillip.append(w)
print(filtered_sentences_phillip)
极简的可复制示例
import nltk
from nltk.corpus import stopwords
nltk.download('stopwords')
stop_words = stopwords.words("english")
sentence = 'Yeah,how are you?'
filtered_sentences = []
for word in sentence.split():
if word not in stop_words:
filtered_sentences.append(word)
print(filtered_sentences)
使用python列表理解的格式更好的可复制示例
import nltk
from nltk.corpus import stopwords
nltk.download('stopwords')
stop_words = stopwords.words("english")
sentence = 'Yeah,how are you?'
filtered_sentences = [word for word in sentence.split() if word not in stop_words]
print(filtered_sentences)
输出
['Yeah,','you?']
请注意,输出为已处理句子的单词列表。如果要将句子作为一个字符串使用,请使用
" ".join(filtered_sentences)
PS:最好在删除停用词之前进行一些词形化或词根提取。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。