NLTK:conllstr2tree 无法正常工作 (Python3)

NLTK: conllstr2tree does not work properly (Python3)

说明我正在尝试做的事情的示例位于 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

您正在从 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 方法:

Return a chunk structure for a single sentence encoded in the given CONLL 2000 style string. This function converts a CoNLL IOB string into a tree. It uses the specified chunk types (defaults to NP, PP and VP), and creates a tree rooted at a node labeled S (by default).

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

token / POS Tag / IOB-Chunk Type

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

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

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