nltk如何将Python中的Tree类型转换为String类型?

How to convert from Tree type to String type in Python by nltk?

for subtree3 in tree.subtrees():
  if subtree3.label() == 'CLAUSE':
    print(subtree3)
    print subtree3.leaves()

使用这段代码我能够提取树的叶子。哪个是: [('talking', 'VBG'), ('constantly', 'RB')] 举个例子。这是完全正确的。现在我希望将此树元素转换为字符串或列表以进行进一步处理。我该怎么做?

我试过的

for subtree3 in tree.subtrees():
  if subtree3.label() == 'CLAUSE':
    print(subtree3)
    print subtree3.leaves()
    fo.write(subtree3.leaves())
fo.close()

但是它抛出一个错误:

Traceback (most recent call last):
  File "C:\Python27\Association_verb_adverb.py", line 35, in <module>
    fo.write(subtree3.leaves())
TypeError: expected a character buffer object

我只想将树叶存储在文本文件中。

这取决于您的 NLTK 版本和 Python。我认为您在 nltk.tree 模块中引用了 Tree class。如果是,请继续阅读。

在您的代码中,确实是:

  1. subtree3.leaves() returns 一个 "list of tuple" 对象和
  2. fo是一个PythonFile IO objectfo.write只接收一个str类型作为参数

你可以简单地用 fo.write(str(subtree3.leaves())) 打印树叶,因此:

for subtree3 in tree.subtrees():
    if subtree3.label() == 'CLAUSE':
        print(subtree3)
        print subtree3.leaves()
        fo.write(str(subtree3.leaves()))
fo.flush()
fo.close()

并且不要忘记 flush() 缓冲区。

可能问题更多是尝试将元组列表写入文件而不是遍历 NLTK Tree 对象。参见 and Unpacking a list / tuple of pairs into two lists / tuples

要输出 2 个字符串的元组列表,我发现使用这个习惯用法很有用:

fout = open('outputfile', 'w')

listoftuples = [('talking', 'VBG'), ('constantly', 'RB')]
words, tags = zip(*listoftuples)

fout.write(' '.join(words) + '\t' + ' '.join(tags) + '\n')

但是如果您的子树中有多个级别,zip(*list) 代码可能无法工作。