可以通过使用nltk.tokenize删除一些不必要的停止词来标记字符串。但是,如何在删除其他停止词的同时,将包含秒词的短语标记为单个标记呢?
例如:
投入:特朗普是美国总统。
产出:特朗普,“美国总统”
我如何才能得到的结果,只是删除'is‘和第一个’但不删除‘的’和第二个‘?
发布于 2019-04-15 18:49:43
您可以使用nltk的多字表达式托卡器,它允许将多个单词表达式合并为单个标记。您可以创建多个单词表达式的词汇表,并向其中添加如下条目:
from nltk.tokenize import MWETokenizer
mwetokenizer = MWETokenizer([('President','of','the','United','States')], separator=' ')
mwetokenizer.add_mwe(('President','of','France'))请注意,MWETokenizer将一个标记化文本列表作为输入,并重新标记它。所以,首先标记句子例如。使用word_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', '.']https://stackoverflow.com/questions/55695050
复制相似问题