我有一个NLTK树对象,其中有6个NP块。
t1 = Tree('S', [('现在', 'T'), ('每', 'RZ'), ('次', 'QV'), ('打火', 'VN'), ('比较', 'D'), ('反感', 'V'), Tree('NP', [('悦动', 'NZ')]), Tree('NP', [('打火', 'VI'), ('时', 'TG'), ('比较', 'D'), ('嘈杂', 'A'), ('的', 'UDE1'), ('声音', 'N')]), (',', 'WD'), ('当然', 'D'), Tree('NP', [('比', 'P')]), Tree('NP', [('面包车', 'N')]), Tree('NP', [('打火', 'VI'), ('的', 'UDE1'), ('声音', 'N')]), Tree('NP', [('算是', 'V'), ('好听', 'A'), ('的', 'UDE1')]), ('!', 'WT')])我希望将这个t1保存在硬盘中,所以我将它写入如下所示的文件中。
>>> print(t1)
(S
现在/T
每/RZ
次/QV
打火/VN
比较/D
反感/V
(NP 悦动/NZ)
(NP 打火/VI 时/TG 比较/D 嘈杂/A 的/UDE1 声音/N)
,/WD
当然/D
(NP 比/P)
(NP 面包车/N)
(NP 打火/VI 的/UDE1 声音/N)
(NP 算是/V 好听/A 的/UDE1)
!/WT)
>>> file.write(t1.__str__())由于t1保存在一个文件中,我尝试用BracketParseCorpusReader从一个文件中重新加载它,但是它工作得不太好。
# nltk.corpus.__init__.py
bracket2 = LazyCorpusLoader(
'Bracket2', BracketParseCorpusReader, r'car/.*\.txt', encoding='utf8')
>>> bracket2.tagged_words() # Bracket2 is a instance of BracketParseCorpusReader
[('悦动/NZ', 'NP'), ('比/P', 'NP'), ('面包车/N', 'NP'), ...]
# failed to load words other than NP chunk
>>> bracket2.tagged_words()[0]
('悦动/NZ', 'NP')
# failed to load the first word "现在/T"
>>> bracket2.tagged_sents()[0]
[('悦动/NZ', 'NP'), ('比/P', 'NP'), ('面包车/N', 'NP')]
# failed to load the whole sentence读者看不出单词和标签。它似乎给了一些适当的参数关于POS分离器,sent_tokenizer,但我不知道如何定制它。
t1?发布于 2015-04-02 12:00:19
如果我的理解是正确的,你想要保存一棵树,然后再“解释”那棵树,对吗?
使用tree.fromstring()可能是一种方法:
import nltk
t = nltk.tree.Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")它做的正是这个名字的意思;)
另见模块/nltk/tree.html
希望这能有所帮助!
https://stackoverflow.com/questions/29302267
复制相似问题