You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从句子中提取仅有的名词?NLTK pos_tag提取结果异常求助

解决NLTK精准提取名词的问题

你的问题出在判断条件太宽泛——仅通过标签以"N"开头来筛选,可能误匹配非名词标签(或你的环境中词性标注结果异常)。要精准提取名词,需明确匹配Penn Treebank词性标注体系中的专属名词标签:

  • NN:单数普通名词
  • NNS:复数普通名词
  • NNP:单数专有名词
  • NNPS:复数专有名词

修改后的代码

from nltk.tokenize import word_tokenize
from nltk.tag import pos_tag

def Noun(sentence):
    lista = []
    words = word_tokenize(sentence)
    pos = pos_tag(words)
    # 定义所有合法的名词标签集合
    noun_tags = {'NN', 'NNS', 'NNP', 'NNPS'}
    # 直接遍历pos_tag返回的(word, tag)元组,无需索引
    for word, tag in pos:
        if tag in noun_tags:
            lista.append(word)
    return pos, lista

验证示例

调用Noun("let's talk to Thomas and check if he will come to the party"),会得到期望的输出:

['Thomas', 'party']

额外注意事项

确保你已下载NLTK所需的分词和词性标注模型,否则会导致标注结果异常:

import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')

内容的提问来源于stack exchange,提问作者Taetae

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 16:55:23