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

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

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

这会根据给定的文本生成树。
我编写的代码旨在使用文本文件中的输入。 因此,打开它后,我使用 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. 查找 block 类型
  3. 添加适当的 IOB 标签。

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

关于python - NLTK:conllstr2tree 无法正常工作(Python3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32671399/

相关文章:

python - itertools.chain.from_iterable 适用于嵌套数字列表,但不适用于字符串列表?

r - 使用MSE在MLR上分割决策树

machine-learning - 如何在 sklearn 中使用 SelectFromModel 查找类的积极信息特征

matlab - matlab中的贝叶斯分类

php - 如何使用python绕过WP super 缓存?

python - 在 Python 中的字符前添加零

python - post_save.disconnect 根本不起作用

python-3.x - 多处理显示 matplotlib 图

javascript - 登录 JavaScript 登录表单请求

python-3.x - 如何更改Flet中的加载标志?