加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-17 17:42:01 所属栏目:Python 来源:网络整理
导读:该问题与以下内容完全相同:????????????????????????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 MWETokenizer
mwetokenizer = MWETokenizer([('President','of','the','United','States')],separator=' ')
mwetokenizer.add_mwe(('President','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','President of the United States',','and','Macron','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','.']

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读