简体   繁体   English

编写空格分隔的文本以使其在Python#2中易于阅读

[英]Writing white-space delimited text to be human readable in Python #2

I want to write a 2D numpy array into a human-readable text file format. 我想将2D numpy数组写入人类可读的文本文件格式。 I came across this question asked before but it only specifies equal number of space to be associated with each element in the array. 我遇到了之前问过的这个问题,但它只指定了与数组中每个元素关联的相等数量的空间。 In it all elements are spaced out with 10 spaces. 在其中所有元素都以10个空格隔开。 What I want is different number of space for each column in my array. 我想要的是数组中每列的不同数量的空间。

Writing white-space delimited text to be human readable in Python 编写空格分隔的文本以使其在Python中易于阅读

For example, I want 7 spaces for my 1st column, 10 spaces for my 2nd column, 4 spaces for my 3rd column, etc. Is there an analogy to numpy.savetxt(filename, X, delimiter = ',', fmt = '%-10s'), but where instead of '%-10s' I have say '%-7s, %-10s, %-4s' etc? 例如,我想要第一列7个空格,第二列10个空格,第三列4个空格,依此类推。是否有类似于numpy.savetxt(filename,X,delimiter =',',fmt =' %-10s'),但是我说的是“%-7s,%-10s,%-4s”等而不是“%-10s”?

Thank you 谢谢

Here is an example of what it can look like (Python2&3): 这是一个看起来像(Python2&3)的示例:

l = [[1,2,3,4], [3,4,5,6]]
for row in l:
    print(u'{:<7} {:>7} {:^7} {:*^7}'.format(*row))

1             2    3    ***4***
3             4    5    ***6***

The formatting options are taken from http://docs.python.org/2/library/string.html 格式设置选项取自http://docs.python.org/2/library/string.html

>>> '{:<30}'.format('left aligned')
'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')  # use '*' as a fill char
'***********centered***********'

If you need a file, then do this: 如果需要文件,请执行以下操作:

l = [[1,2,3,4], [3,4,5,6]]
with open('file.txt', 'wb') as f:
    f.write(u'\ufeff'.encode('utf-8'))
    for row in l:
        line = u'{:<7} {:>7} {:^7} {:*^7}\r\n'.format(*row)
        f.write(line.encode('utf-8'))

The content of the file is 该文件的内容是

1             2    3    ***4***
3             4    5    ***6***

And the encoding is UTF-8. 编码为UTF-8。 This means that you can have not only numbers but also any letter in your heading: ☠ ⇗ ⌚ ② ☕ ☃ ⛷ 这意味着标题中不仅可以包含数字,还可以包含任何字母: ☠☠②☕☃

heading = [u'☠', u'⇗', u'⌚', u'②']
with open('file.txt', 'wb') as f:
    f.write(u'\ufeff'.encode('utf-8'))
    line = '{:<7} {:>7} {:^7} {:*^7}\r\n'.format(*heading)
    f.write(line.encode('utf-8'))
    for row in l:
        line = '{:<7} {:>7} {:^7} {:*^7}\r\n'.format(*row)
        f.write(line.encode('utf-8'))

☠             ⇗    ⌚    ***②***
1             2    3    ***4***
2             3    4    ***5***

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

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