【问题标题】:How to center align text produced by numpy.savetxt?如何居中对齐 numpy.savetxt 生成的文本?
【发布时间】:2013-03-11 10:26:25
【问题描述】:

我在numpy.savetxt 周围使用了一个小包装器来自动生成标题名称并为可读的输出创建某种智能的宽度对齐方式。一个更简单的解决方案是this answer

我想知道如何指定宽度并使输出文本与中心对齐,而不是像文档中所示的那样左对齐。

numpy.savetxt 文档中,我看到了以下信息:

Notes
-----
Further explanation of the `fmt` parameter
(``%[flag]width[.precision]specifier``):
flags:
    ``-`` : left justify

    ``+`` : Forces to preceed result with + or -.

    ``0`` : Left pad the number with zeros instead of space (see width).

width:
    Minimum number of characters to be printed. The value is not truncated
    if it has more characters.

文档指向python mini format specification 的更“详尽的资源”,但那里的信息与对齐信息不兼容。

各种对齐选项的含义如下:

Option  Meaning
'<'     Forces the field to be left-aligned within the available space (this is the default for most objects).
'>'     Forces the field to be right-aligned within the available space (this is the default for numbers).
'='     Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types.
'^'     Forces the field to be centered within the available space.

不兼容是因为 savetxt 不接受 '^' 作为有效的格式字符。任何人都可以阐明如何在“numpy.savetxt”中指定格式以使输出居中对齐吗?

【问题讨论】:

    标签: python numpy alignment center


    【解决方案1】:

    您可以使用format 组合更复杂的格式选项,包括居中的'^' 标志:

    import numpy as np
    a = np.ones((3,3))*100
    a[1,1]=111.12321
    a[2,2]=1
    np.savetxt('tmp.txt',a, fmt='{:*^10}'.format('%f'))
    

    给予:

    ****100.000000**** ****100.000000**** ****100.000000****
    ****100.000000**** ****111.123210**** ****100.000000****
    ****100.000000**** ****100.000000**** ****1.000000****
    

    【讨论】:

    • 您对**** 的加入让我有点困惑。我检查了它,它确实回答了我的问题。谢谢你。我最终使用fmt='{0: ^{1}}'.format(fmtname, fieldlen),其中fmtnamenp.savetxt 可接受的格式规范之一。
    • 是的,我只是用这个来描述中心化效果...谢谢!
    猜你喜欢
    • 2013-05-13
    • 2013-01-09
    • 1970-01-01
    • 2016-02-11
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    相关资源
    最近更新 更多