【问题标题】:NLTK: conllstr2tree does not work properly (Python3)NLTK:conllstr2tree 无法正常工作(Python3)
【发布时间】:2015-09-19 17:46:56
【问题描述】:

http://www.nltk.org/book/ch07.html 的第 3.1 部分中的示例说明了我正在尝试做的事情

本质上是这样的:

import nltk
text = " ..... "  #Whatever the text should be
nltk.chunk.conllstr2tree(text, chunk_types=['NP']).draw()

这会根据给定的text 生成树。
我编写的代码试图使用来自文本文件的输入。 所以打开它后,我使用readlines 来获取它的字符串版本。

import nltk, re, pprint
f = open('sample.txt', 'r')
f1 = f.read().strip()
f2 = ' '.join(f1.split())
nltk.chunk.conllstr2tree(f2, chunk_types=['NP']).draw()

我得到的错误是:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-768af8cd2f77> in <module>()
      3 f1 = f.read().strip()
      4 f2 = ' '.join(f1.split())
----> 5 nltk.chunk.conllstr2tree(f2, chunk_types=['NP']).draw()

/usr/local/lib/python3.4/dist-packages/nltk/chunk/util.py in conllstr2tree(s, chunk_types, root_label)
    380         match = _LINE_RE.match(line)
    381         if match is None:
--> 382             raise ValueError('Error on line %d' % lineno)
    383         (word, tag, state, chunk_type) = match.groups()
    384 

ValueError: Error on line 0

【问题讨论】:

  • 你想做什么?块NP?识别命名实体?完全不同的东西?从你的 sn-p 看一点都不清楚。

标签: python python-3.x machine-learning nlp nltk


【解决方案1】:

您正在传递来自 sample.txt 的原始字符串数据,修剪空格 f1,然后标记空格 f2

如果您查看the example from the NTLK book,他们提到了分块方法,

nltk.chunk.conllstr2tree(text, chunk_types=['NP']).draw()

text 变量是一个 IOB 标记数据序列,如下所示:

text = """
   he PRP B-NP
   accepted VBD B-VP
   the DT B-NP
   position NN I-NP
   of IN B-PP
   vice NN B-NP
   chairman NN I-NP
   of IN B-PP
   Carlyle NNP B-NP
   Group NNP I-NP
   , , O
   a DT B-NP
   merchant NN I-NP
   banking NN I-NP
   concern NN I-NP
   . . O
"""

根据source code 文档,conllstr2tree 方法:

返回单个句子的块结构 在给定的 CONLL 2000 样式字符串中编码。 此函数将 CoNLL IOB 字符串转换为树。 它使用指定的块类型 (默认为 NP、PP 和 VP),并创建以节点为根的树 标记为 S(默认)。

问题在于您没有传递正确的格式(CoNLL 2000 Wall Street Journal),它应该看起来像这样(没有斜线):

token / POS Tag / IOB-Chunk Type

所以你需要几个额外的步骤:

  1. 为每个单词找到可能的词性标签。
  2. 查找块类型
  3. 添加适当的 IOB 标记。

提供一个示例代码 sn-p 是不合理的(对于一个 SO 问题),因为这需要大量的工作,但希望这会为您指明正确的方向!

【讨论】:

  • 很好的解释。 OP 引用的 NLTK 书籍章节给出了编写和训练分块器的完整代码;只需通读本章并获得相关部分。
  • 谢谢!是的,好点。感谢您指出了这一点!他应该很快就会摇摆不定。
猜你喜欢
  • 1970-01-01
  • 2021-01-23
  • 2016-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-01
  • 2012-07-11
相关资源
最近更新 更多