Linux和Windows上的代码输出各不相同,我对编码不太熟悉,这就是这个问题所涉及的。你知道吗
这是我的密码:
import sys
from treelib import Tree
from io import StringIO
# creating and populating tree
tree = Tree()
tree.create_node("Harry", "harry") # root node
tree.create_node("Jane", "jane", parent="harry")
tree.create_node("Bill", "bill", parent="harry")
tree.create_node("Diane", "diane", parent="jane")
tree.create_node("Mary", "mary", parent="diane")
tree.create_node("Mark", "mark", parent="jane")
# var to store standard output
output = StringIO()
sys.stdout = output
tree.show()
# restoring standard output to console
sys.stdout = sys.__stdout__
tree_structure = output.getvalue()
print(tree_structure)
我在Linux上得到了预期的输出,但在Windows上结果的字符编码为\xNN。你知道吗
Linux输出:
Harry
├── Bill
└── Jane
├── Diane
│ └── Mary
└── Mark
Windows输出:
b'Harry\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Bill\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 Jane\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Diane\n \xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 Mary\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 Mark\n'
尽管在windows和linux上,sys.stdout.encoding
的结果都是'utf-8'
。你知道吗
最接近预期输出的方法是在print语句之前添加以下内容:
#removing b'' from string
tree_structure = tree_structure[2:-2]
# converting to bytes
tree_structure = bytes(tree_structure,'utf-8')
tree_structure = tree_structure.decode('unicode_escape')
print(tree_structure)
之后输出:
Harry
âââ Bill
âââ Jane
âââ Diane
â âââ Mary
âââ Mark
这很可能是Windows终端的问题,而不是代码的问题。你知道吗
尝试在控制台中设置
chcp 65001
,这会将代码页更改为UTF-8。print("├")
在那之后对我有效。你知道吗https://technet.microsoft.com/en-us/library/bb490874.aspx
我能够通过使用codecs获得预期的输出。这个 answer帮助了我。 使用编解码器工作。你知道吗
相关问题 更多 >
编程相关推荐