gpt4 book ai didi

python - 如何通过nltk在Python中将Tree类型转换为String类型?

转载 作者:太空宇宙 更新时间:2023-11-03 13:14:38 25 4
gpt4 key购买 nike

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 版本。我想你指的是 Tree nltk.tree 模块中的类。如果是这样,请继续阅读。

在您的代码中,确实:

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

关于python - 如何通过nltk在Python中将Tree类型转换为String类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33901232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com