我想以视觉方式查看下面的结果是否是我需要的:
import nltk
sentence = [("the", "DT"), ("little", "JJ"), ("yellow", "JJ"), ("dog", "NN"), ("barked","VBD"), ("at", "IN"), ("the", "DT"), ("cat", "NN")]
pattern = """NP: {<DT>?<JJ>*<NN>}
VBD: {<VBD>}
IN: {<IN>}"""
NPChunker = nltk.RegexpParser(pattern)
result = NPChunker.parse(sentence)
来源:https://stackoverflow.com/a/31937278/3552975
我不解释为什么我不能对result
进行漂亮的打印。
result.pretty_print()
该错误显示为TypeError: not all arguments converted during string formatting
。我使用Python3.5,nltk3.3。
答案 0 :(得分:2)
如果要查找带括号的解析输出,则可以使用Tree.pprint()
:
>>> import nltk
>>> sentence = [("the", "DT"), ("little", "JJ"), ("yellow", "JJ"), ("dog", "NN"), ("barked","VBD"), ("at", "IN"), ("the", "DT"), ("cat", "NN")]
>>>
>>> pattern = """NP: {<DT>?<JJ>*<NN>}
... VBD: {<VBD>}
... IN: {<IN>}"""
>>> NPChunker = nltk.RegexpParser(pattern)
>>> result = NPChunker.parse(sentence)
>>> result.pprint()
(S
(NP the/DT little/JJ yellow/JJ dog/NN)
(VBD barked/VBD)
(IN at/IN)
(NP the/DT cat/NN))
但是很可能您正在寻找
S
_________________|_____________________________
NP VBD IN NP
________|_________________ | | _____|____
the/DT little/JJ yellow/JJ dog/NN barked/VBD at/IN the/DT cat/NN
让我们深入研究Tree.pretty_print()
https://github.com/nltk/nltk/blob/develop/nltk/tree.py#L692中的代码:
def pretty_print(self, sentence=None, highlight=(), stream=None, **kwargs):
"""
Pretty-print this tree as ASCII or Unicode art.
For explanation of the arguments, see the documentation for
`nltk.treeprettyprinter.TreePrettyPrinter`.
"""
from nltk.treeprettyprinter import TreePrettyPrinter
print(TreePrettyPrinter(self, sentence, highlight).text(**kwargs),
file=stream)
它正在创建TreePrettyPrinter
对象https://github.com/nltk/nltk/blob/develop/nltk/treeprettyprinter.py#L50
class TreePrettyPrinter(object):
def __init__(self, tree, sentence=None, highlight=()):
if sentence is None:
leaves = tree.leaves()
if (leaves and not any(len(a) == 0 for a in tree.subtrees())
and all(isinstance(a, int) for a in leaves)):
sentence = [str(a) for a in leaves]
else:
# this deals with empty nodes (frontier non-terminals)
# and multiple/mixed terminals under non-terminals.
tree = tree.copy(True)
sentence = []
for a in tree.subtrees():
if len(a) == 0:
a.append(len(sentence))
sentence.append(None)
elif any(not isinstance(b, Tree) for b in a):
for n, b in enumerate(a):
if not isinstance(b, Tree):
a[n] = len(sentence)
sentence.append('%s' % b)
self.nodes, self.coords, self.edges, self.highlight = self.nodecoords(
tree, sentence, highlight)
看起来出现错误的行是sentence.append('%s' % b)
https://github.com/nltk/nltk/blob/develop/nltk/treeprettyprinter.py#L97
问题是为什么会引发TypeError ?
TypeError: not all arguments converted during string formatting
如果仔细看,看起来我们可以对大多数基本的python类型使用print('%s' % b)
# String
>>> x = 'abc'
>>> type(x)
<class 'str'>
>>> print('%s' % x)
abc
# Integer
>>> x = 123
>>> type(x)
<class 'int'>
>>> print('%s' % x)
123
# Float
>>> x = 1.23
>>> type(x)
<class 'float'>
>>> print('%s' % x)
1.23
# Boolean
>>> x = True
>>> type(x)
<class 'bool'>
>>> print('%s' % x)
True
令人惊讶的是,它甚至可以在列表中使用!
>>> x = ['abc', 'def']
>>> type(x)
<class 'list'>
>>> print('%s' % x)
['abc', 'def']
但是它受tuple
的阻碍!
>>> x = ('DT', 123)
>>> x = ('abc', 'def')
>>> type(x)
<class 'tuple'>
>>> print('%s' % x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
因此,如果我们回到https://github.com/nltk/nltk/blob/develop/nltk/treeprettyprinter.py#L95的代码
if not isinstance(b, Tree):
a[n] = len(sentence)
sentence.append('%s' % b)
由于我们知道sentence.append('%s' % b)
无法处理tuple
,因此添加元组类型检查并以某种方式将元组中的项目连接起来并转换为str
会产生很好的{{ 1}}:
pretty_print
[输出]:
if not isinstance(b, Tree):
a[n] = len(sentence)
if type(b) == tuple:
b = '/'.join(b)
sentence.append('%s' % b)
在不更改 S
_________________|_____________________________
NP VBD IN NP
________|_________________ | | _____|____
the/DT little/JJ yellow/JJ dog/NN barked/VBD at/IN the/DT cat/NN
代码的情况下,仍然可以获得漂亮的印刷品吗?
让我们看看nltk
即result
对象的样子:
Tree
看起来叶子被保留为字符串元组列表,例如Tree('S', [Tree('NP', [('the', 'DT'), ('little', 'JJ'), ('yellow', 'JJ'), ('dog', 'NN')]), Tree('VBD', [('barked', 'VBD')]), Tree('IN', [('at', 'IN')]), Tree('NP', [('the', 'DT'), ('cat', 'NN')])])
,因此我们可以进行一些修改,使其成为字符串列表,例如[('the', 'DT'), ('cat', 'NN')]
,这样[('the/DT'), ('cat/NN')]
会表现出色。
因为我们知道Tree.pretty_print()
有助于将字符串的元组连接到所需的形式,即
Tree.pprint()
我们可以简单地输出到带括号的解析字符串,然后用(S
(NP the/DT little/JJ yellow/JJ dog/NN)
(VBD barked/VBD)
(IN at/IN)
(NP the/DT cat/NN))
重新读取解析的Tree
对象:
Tree.fromstring()
完成:
from nltk import Tree
Tree.fromstring(str(result)).pretty_print()
[输出]:
import nltk
sentence = [("the", "DT"), ("little", "JJ"), ("yellow", "JJ"), ("dog", "NN"), ("barked","VBD"), ("at", "IN"), ("the", "DT"), ("cat", "NN")]
pattern = """NP: {<DT>?<JJ>*<NN>}
VBD: {<VBD>}
IN: {<IN>}"""
NPChunker = nltk.RegexpParser(pattern)
result = NPChunker.parse(sentence)
Tree.fromstring(str(result)).pretty_print()