【问题标题】:nltk NER word extractionnltk NER 词提取
【发布时间】:2015-01-07 21:19:15
【问题描述】:

我检查了以前的相关主题,但没有解决我的问题。我已经编写了从文本中获取 NER 的代码。

text = "Stallone jason's film Rocky was inducted into the National Film Registry as well as having its film props placed in the Smithsonian Museum."

tokenized = nltk.word_tokenize(text)
tagged = nltk.pos_tag(tokenized)
namedEnt = nltk.ne_chunk(tagged, binary = True)
print namedEnt
namedEnt = nltk.ne_chunk(tagged, binary = False)

结果很短

(S
  (NE Stallone/NNP)
  jason/NN
  's/POS
  film/NN
  (NE Rocky/NNP)
  was/VBD
  inducted/VBN
  into/IN
  the/DT
  (NE National/NNP Film/NNP Registry/NNP)
  as/IN
  well/RB
  as/IN
  having/VBG
  its/PRP$
  film/NN
  props/NNS
  placed/VBN
  in/IN
  the/DT
  (NE Smithsonian/NNP Museum/NNP)
  ./.)

虽然我希望结果只有 NE,比如

Stallone
Rockey
National Film Registry
Smithsonian Museum

如何做到这一点?

更新

result = ' '.join([y[0] for y in x.leaves()]) for x in namedEnt.subtrees() if x.node == "NE"
print result

给出语法错误,正确的写法是什么?

更新2

text = "史泰龙杰森的电影《洛奇》被列入国家电影登记处,其电影道具被放置在史密森尼博物馆。"

tokenized = nltk.word_tokenize(text)
tagged = nltk.pos_tag(tokenized)
namedEnt = nltk.ne_chunk(tagged, binary = True)
print namedEnt
np = [' '.join([y[0] for y in x.leaves()]) for x in namedEnt.subtrees() if x.node == "NE"]
print np

错误:

 np = [' '.join([y[0] for y in x.leaves()]) for x in namedEnt.subtrees() if x.node == "NE"]
  File "/usr/local/lib/python2.7/dist-packages/nltk/tree.py", line 198, in _get_node
    raise NotImplementedError("Use label() to access a node label.")
NotImplementedError: Use label() to access a node label.

所以我尝试了

np = [' '.join([y[0] for y in x.leaves()]) for x in namedEnt.subtrees() if x.label() == "NE"]

结果为空

【问题讨论】:

    标签: python regex nlp nltk


    【解决方案1】:

    返回的namedEnt 实际上是一个Tree 对象,它是list 的子类。您可以执行以下操作来解析它:

    [' '.join([y[0] for y in x.leaves()]) for x in namedEnt.subtrees() if x.node == "NE"]
    

    输出:

    ['Stallone', 'Rocky', 'National Film Registry', 'Smithsonian Museum']
    

    binary 标志设置为True 将仅指示子树是否为 NE,这正是我们上面所需要的。当设置为False 时,它将提供更多信息,例如 NE 是否为组织、人员等。由于某种原因,标记 On 和 Off 的结果似乎彼此不一致。

    【讨论】:

    • 非常感谢,但是这个怎么用呢?我更新了问题,仍然出现错误
    • 它是一个列表理解,所以你必须像result = [' '.join([y[0] for y in x.leaves()]) for x in namedEnt.subtrees() if x.node == "NE"]一样将它嵌入到'[]'中
    • 另外,与binary=True一起使用
    • 谢谢,但还是有问题,请查看有问题的update2
    • 是的。我有一个旧版本。在新版本的 nltk 中没有node() 功能。但是更新我的 nltk 后,您的行 np = [' '.join([y[0] for y in x.leaves()]) for x in namedEnt.subtrees() if x.label() == "NE"] 对我有用。尝试进一步调试,例如查看 namedEnt 中的内容
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多