【问题标题】:How to convert from Tree type to String type in Python by nltk?如何通过 nltk 在 Python 中将 Tree 类型转换为 String 类型?
【发布时间】:2016-02-27 08:11:31
【问题描述】:
for subtree3 in tree.subtrees():
  if subtree3.label() == 'CLAUSE':
    print(subtree3)
    print subtree3.leaves()

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

我尝试了什么

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

我只想将叶子存储在一个文本文件中。

【问题讨论】:

  • 您的输入是什么,您希望输出什么?能给我举个例子吗?在最顶层的子树中也可以有多个层,因此根据您需要的输出,您遍历树以将其打印出来的方式会有所不同

标签: python list tree tuples nltk


【解决方案1】:

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

在您的代码中,确实:

  1. subtree3.leaves() 返回一个“元组列表”对象,
  2. fo 是 Python File 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() 缓冲区。

【讨论】:

  • @Iguiel 这正是我想要的。非常感谢。
【解决方案2】:

可能问题更多的是尝试将元组列表写入文件,而不是遍历 NLTK Tree 对象。见NLTK: How do I traverse a noun phrase to return list of strings?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) 代码可能不起作用。

【讨论】:

  • 我很高兴这个答案有帮助 =)
  • @alvas f 我们的子树中有多个级别,我们如何将树写入 txt 文件?因为,正如你所说,在这种情况下不可能使用zip(*list)
猜你喜欢
  • 2016-03-20
  • 2019-12-02
  • 2019-10-23
  • 2017-01-29
  • 1970-01-01
  • 1970-01-01
  • 2016-05-20
  • 1970-01-01
  • 2019-07-23
相关资源
最近更新 更多