【问题标题】:Spacy get pos & tag for specific wordSpacy 获取特定单词的位置和标签
【发布时间】:2019-02-20 10:25:26
【问题描述】:

我遇到了一种情况,我必须从 spacy doc 对象中获取 pos_ 和 tag_。

例如,

text = "Australian striker John hits century"
doc = nlp(text)
for nc in doc.noun_chunks:
    print(nc) #Australian striker John
doc[1].tag_ # gives for striker

如果我想得到 pos_tag_ 的单词“前锋”,我需要再次将那句话给 nlp() 吗??

还有 doc[1].tag_ 在那里,但我需要类似 doc['striker'].tag_ ..

有没有可能?

【问题讨论】:

  • 嗯,首先,如果句子中有多个“前锋”字样,doc['striker'].tag_ 之类的内容就会模棱两可。但是关于您最初的问题,do I need to again give that sentence 是什么意思?您已经拥有doc[1].tag_ == 'NN'doc[1].pos_ == 'NOUN'
  • "我需要再把那句话给nlp()吗?"是的,因为 POS 标签取决于上下文。例如,没有上下文的“命中”可以是名词(“命中”的复数)或动词。您可能可以将每个标记映射到它们的位置并执行doc[index[word]] 之类的操作,但如果同一个单词出现多次,则会出现问题。
  • 好的。我认为您不需要多次解析一个句子。当doc 准备就绪时,所有位置都已根据您所说的上下文正确计算。你可以做print([token.pos_ for token in doc])它返回['ADJ', 'NOUN', 'PROPN', 'VERB', 'NOUN']
  • @darksky 但是如何仅获取检测到的名词块的标签.. 就像有大段落一样。?
  • @VivekAnanthan 名词块是spacy.tokens.span.Span,而不是标记。您必须对其进行迭代以打印块内每个令牌的标签,例如 print([[token.tag_ for token in nc] for nc in doc.noun_chunks])

标签: python nlp spacy tagging part-of-speech


【解决方案1】:

您只需处理一次文本:

text = "Australian striker John hits century"
doc = nlp(text)
for nc in doc.noun_chunks:
    print(nc)  
    print([(token.text, token.tag_, token.pos_) for token in nc])

如果您只想获取名词块中的特定单词,您可以通过将第二个打印语句更改为 e.g. 来进一步过滤它

print([(token.text, token.tag_, token.pos_) for token in nc if token.tag_ == 'NN'])

请注意,这可能会打印多个匹配项,具体取决于您的模型和输入句子。

【讨论】:

    【解决方案2】:

    您可以执行以下操作:

    text = "Australian striker John hits century"
    x1 = "striker"
    x2 = re.compile(x1,re.IGNORECASE | re.VERBOSE)
    loc_indexes = [m.start(0) for m in re.finditer(x2, text )]
    tag = [i.tag_ for i in nlp(text) if i.idx in loc_indexes ]
    print(x1,tag[0])
    

    它给出输出: striker NN

    如果需要,您还可以轻松地将其设置为动态,并将 x1 作为变量。

    【讨论】:

      猜你喜欢
      • 2019-11-30
      • 2012-07-22
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      相关资源
      最近更新 更多