繁体   English   中英

如何通过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')]它们是: [('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

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

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

在您的代码中,确实如此:

  1. subtree3.leaves()返回“元组列表”对象,
  2. fo是一个Python File IO对象fo.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对象。 请参阅NLTK:如何遍历名词短语以返回字符串列表? 并将列表/元组解包为两个列表/元组

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

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

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

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

但是如果子树中有多个级别,则zip(*list)代码可能不起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM