如何使用Python nltk.tokenize将包含stopwords的短语视为单个标记

如何使用Python nltk.tokenize将包含stopwords的短语视为单个标记,python,nltk,tokenize,stop-words,Python,Nltk,Tokenize,Stop Words,可以通过使用删除一些不必要的停止字来标记字符串。但如何将包含stopwords的短语标记为单个标记,同时删除其他stopwords 例如: 投入:特朗普是美国总统 产出:[“特朗普”、“美国总统”] 如何得到只删除“是”和第一个“the”,但不删除“of”和第二个“the”的结果?您可以使用nltk,它允许将多单词表达式合并到单个标记中。您可以创建多单词表达式的词典,并向其中添加条目,如下所示: from nltk.tokenize import MWETokenizer mwetokenize

可以通过使用删除一些不必要的停止字来标记字符串。但如何将包含stopwords的短语标记为单个标记,同时删除其他stopwords

例如:

投入:特朗普是美国总统

产出:[“特朗普”、“美国总统”]

如何得到只删除“是”和第一个“the”,但不删除“of”和第二个“the”的结果?

您可以使用nltk,它允许将多单词表达式合并到单个标记中。您可以创建多单词表达式的词典,并向其中添加条目,如下所示:

from nltk.tokenize import MWETokenizer
mwetokenizer = MWETokenizer([('President','of','the','United','States')], separator=' ')
mwetokenizer.add_mwe(('President','of','France'))
请注意,MWETokenizer将标记化文本列表作为输入,并对其重新标记。因此,首先用
word\u tokenize()
标记句子,然后将其输入MWETokenizer:

from nltk.tokenize import word_tokenize
sentence = "Trump is the President of the United States, and Macron is the President of France."
mwetokenized_sentence = mwetokenizer.tokenize(word_tokenize(sentence))
# ['Trump', 'is', 'the', 'President of the United States', ',', 'and', 'Macron', 'is', 'the', 'President of France', '.']
然后,过滤掉停止词,得到最终过滤的标记化句子:

from nltk.corpus import stopwords
stop_words = set(stopwords.words('english'))
filtered_sentence = [token for token in mwetokenizer.tokenize(word_tokenize(sentence)) if token not in stop_words]
print(filtered_sentence)
输出:

['Trump', 'President of the United States', ',', 'Macron', 'President of France', '.']