简体   繁体   English

如何在python中的txt文件中保存解析树

[英]how to save a parse tree in txt file in python

I am having a problem whenever I try to save a parse tree which is generated from some set of rules which I have specified. 每当我尝试保存由我指定的一组规则生成的解析树时,我都会遇到问题。 all I want to save that parse tree in a new text file. 我想要将该解析树保存在一个新的文本文件中。 when I do this it creates a new text file but it is empty and my code gives an error 当我这样做时,它将创建一个新的文本文件,但它为空,并且我的代码给出了错误

'charmap' codec can't encode characters in position 12-18: character maps to 'charmap'编解码器无法对位置12-18中的字符进行编码:字符映射到

here is my code 这是我的代码

sen = "Heyy Jack whats up"
sent = word_tokenize(sen)
gram = ("""
S -> NP VP
NP -> NU | N N
VP -> NP NP
""")
grammar1 = nltk.cfg.fromstring(gram)
sr_parser = nltk.RecursiveDescentParser(grammar1)
for tree in sr_parser.parse(sent):    
    print(tree)
    values = tree
    with open("new.txt", "w") as output: ## creates new file but empty
        output.write(str(values))

Try using utf-8 encding: 尝试使用utf-8编码:

with open("new.txt", "w", encoding='utf-8') as output: ## creates new file but empty
        output.write(str(values))

You can also use io for python 2 backward compatibility: 您也可以将io用于python 2向后兼容:

import io
with io.open("new.txt", "w", encoding='utf-8') as output: ## creates new file but empty
    output.write(str(values))

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

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