Python 2.7:可能无法正确填充

时间:2019-02-11 15:09:05

标签: python python-2.7 anytree

以下代码未正确填充字符串

    for pre, fill, node in anytree.RenderTree(tree):

        prefix = ("{pre_print}{node_print}".format(pre_print=pre.encode('utf-8'), node_print=node.name)).ljust(120, '-')
        f.write("{pref}> {status}".format(pref=prefix, status=node.status.message()))
        f.write("\n")

我得到的一些输出是(为了便于阅读,我缩短了行填充):

├── modelo_srtm_30_nuevo----------------------------------> No cumple regla
├── modelos_externos--------------------------------------> Ok
│   ├── .snapshot---------------------------------------> No cumple regla
│   ├── 2017 - Aguas Blancas----------------------------> No cumple regla

pre发生更改时,该行的长度不再是应有的长度。

编辑:以下代码演示了该问题,创建了示例树并进行打印:

import anytree


root = anytree.Node(name="root")
child_1 = anytree.Node(name="child_1", parent=root)
grandchild_11 = anytree.Node(name="grandchild_11", parent=child_1)
child_2 = anytree.Node(name="child_2", parent=root)
grandchild_21 = anytree.Node(name="grandchild_21", parent=child_2)
child_3 = anytree.Node(name="child_3", parent=root)
grandchild_31 = anytree.Node(name="grandchild_31", parent=child_3)

filename = "test_tree.txt"

with open(filename, "wt") as f:

    for pre, fill, node in anytree.RenderTree(root):

        prefix = ("{pre_print}{node_print}".format(pre_print=pre.encode('utf-8'), node_print=node.name)).ljust(40, '-')
        f.write("{pref}> {status}".format(pref=prefix, status="testing..."))
        f.write("\n")

1 个答案:

答案 0 :(得分:2)

正如Antti所暗示的,编码后的对齐不会产生非常有效的结果。尝试先对齐然后然后编码:

with open(filename, "wt") as f:
    for pre, fill, node in anytree.RenderTree(root):
        prefix = (u"{pre_print}{node_print}".format(pre_print=pre, node_print=node.name)).ljust(40, '-').encode("utf-8")
        f.write("{pref}> {status}".format(pref=prefix, status="testing..."))
        f.write("\n")

结果:

root------------------------------------> testing...
├── child_1-----------------------------> testing...
│   └── grandchild_11-------------------> testing...
├── child_2-----------------------------> testing...
│   └── grandchild_21-------------------> testing...
└── child_3-----------------------------> testing...
    └── grandchild_31-------------------> testing...