如何用nltk实现Python中树型到字符串型的转换?

2024-05-17 14:55:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

使用这个代码我可以提取出树的叶子。它们是: [('talking', 'VBG'), ('constantly', 'RB')]对于某个例子。这是完全正确的。现在我希望这个树元素转换成字符串或列表中的元素,以便进行进一步的处理。我怎么能做到呢?在

我尝试了什么

^{pr2}$

但它抛出了一个错误:

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

我只想把叶子保存在一个文本文件中。在


Tags: 代码intree元素forifclauselabel
2条回答

问题可能更多的是试图将元组列表写入文件,而不是遍历NLTKTree对象。{和}见^

要输出包含两个字符串的元组列表,我发现使用以下习惯用法很有用:

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

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

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

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

这取决于您的NLTK和Python版本。我想您引用的是nltk.tree模块中的Tree类。如果是这样,请继续读下去。在

在您的代码中,确实:

  1. subtree3.leaves()返回“元组列表”对象
  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()缓冲区。在

相关问题 更多 >