如何使用Python nltk.tokenize将包含停用词的短语作为单个标记对待

如何使用Python nltk.tokenize将包含停用词的短语作为单个标记对待,第1张

概述该问题与以下内容完全相同:            >            How to prevent splitting specific words or phrases and numbers in NLTK?                                    2个可以通过使用nltk.tokenize删除一些不必要的停用词

该问题与以下内容完全相同:            >            How to prevent splitting specific words or phrases and numbers in NLTK?                                    2个
可以通过使用nltk.tokenize删除一些不必要的停用词来对字符串进行令牌化.但是,如何在删除其他停用词的同时将包含停用词的短语令牌化为单个令牌呢?

例如:

输入:特朗普是美国总统.

输出:[“特朗普”,“美国总统”]

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

最佳答案您可以使用nltk的Multi-Word Expression Tokenizer,它可以将多单词表达式合并为单个标记.您可以创建一个包含多词表达式的词典,并向其添加条目,如下所示:

from nltk.tokenize import MWetokenizermwetokenizer = MWetokenizer([('PresIDent','of','the','United','States')],separator=' ')mwetokenizer.add_mwe(('PresIDent','France'))

请注意,MWetokenizer将带标记文本的列表作为输入,然后对其进行重新标记.因此,首先标记该句子.使用word_tokenize(),然后将其输入MWetokenizer:

from nltk.tokenize import word_tokenizesentence = "Trump is the PresIDent of the United States,and Macron is the PresIDent of France."mwetokenized_sentence = mwetokenizer.tokenize(word_tokenize(sentence))# ['Trump','is','PresIDent of the United States',','and','Macron','PresIDent of France','.']

然后,过滤掉停用词以获得最终过滤的标记化句子:

from nltk.corpus import stopwordsstop_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','.']
总结

以上是内存溢出为你收集整理的如何使用Python nltk.tokenize将包含停用词的短语作为单个标记对待 全部内容,希望文章能够帮你解决如何使用Python nltk.tokenize将包含停用词的短语作为单个标记对待 所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1199656.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存