Python格式:如何在数据类型float的数组数据元素之间插入空格

时间:2015-06-12 15:12:36

标签: python format

我有关于格式化的问题。我正在尝试提取相关数据并将此数据插入到fortran文件中。谢天谢地,我正在使用python来完成这项任务。恰好Fortran文件对文本之间的空格数量敏感。所以,这让我想到了我的问题。我的数组数组数据如下:

    [[ -1.80251269  12.14048223  15.47522331]
     [ -2.63865822  13.1656285   15.97462801]
     [ -1.76966256  11.35311123  16.13958474]
     [ -0.76320052  12.45171386  15.34209158]
     [ -2.12634889  11.84315415  14.48020468]]
    [[-14.80251269   1.14048223   1.47522331]
     [ -2.63865822  13.1656285   15.97462801]
     [ -1.76966256  11.35311123  16.13958474]
     [ -0.76320052  12.45171386  15.34209158]
     [ -2.12634889  11.84315415  14.48020468]]
    [[ -0.80251269   0.14048223   0.47522331]
     [ -2.63865822  13.1656285   15.97462801]
     [ -1.76966256  11.35311123  16.13958474]
     [ -0.76320052  12.45171386  15.34209158]
     [ -2.12634889  11.84315415  14.48020468]]

这些元素是浮点数,而不是字符串。例如,我希望数据的第一行(以及之后的每一行)看起来像:

     -1.80251269     12.14048223     15.47522331

我将如何做到这一点?具体来说,有5个空白区域与第一个数字分开左边距,-1.80251269,以及5个空白区域,分隔三个数字中的每一个。另请注意,我需要删除数组括号,但我怀疑我可以使用trim函数执行此操作。抱歉我缺乏知识;我甚至不知道如何开始这个问题,因为我对Python语法的了解有限。任何帮助或提示将不胜感激。谢谢!

编辑:这是我用来生成数组的代码:

     fo = np.genfromtxt("multlines.inp")
     data=scipy.delete(fo, 0, 1)
     txt = np.hsplit(data,3)
     all_data = np.vsplit(data, 4)
     i=0
     num_molecules = int(raw_input("Enter the number of molecules: "))
     print "List of unaltered coordinates:"
     while i < (num_molecules):
          print all_data[i]

5 个答案:

答案 0 :(得分:2)

如果您使用的是NumPy,则可以使用import webbrowser import websockets import asyncio class fmDaemon( Daemon): def __init__( self, me): self.me = me def run( self): @asyncio.coroutine def coroutine_daemon_websocket_server(websocket, path): msg = yield from websocket.recv() if msg != None: msg_out = "{}".format( msg) yield from websocket.send( msg_out) self.me = Function1( self.me, msg) loop = asyncio.get_event_loop() loop.run_until_complete(websockets.serve(coroutine_daemon_websocket_server, self.me.IP, self.me.PORT)) loop.run_forever() @asyncio.coroutine def Function1(me, msg): @asyncio.coroutine def coroutine_overlay_websocket_server(websocket, path): while True: msg = yield from websocket.recv() msg_out = "{}".format( msg) yield from websocket.send( msg_out) if msg == 'my_expected_string': me.flags['myStr'] = msg break event.set() # Tell the outer function it can exit. event = asyncio.Event() yield from websockets.serve(coroutine_overlay_websocket_server, me.IP, me.PORT_overlay)) yield from event.wait() # This will block until event.set() is called.

np.savetxt

获得

np.savetxt('a.txt', a.reshape(15,3), '%16.8f')

(您需要将阵列重塑为二维以执行我认为您想要的操作)。

答案 1 :(得分:1)

如果您将数据格式化为列表,那么我怀疑@ kamik423的答案会对您有所帮助。如果格式化为字符串,您可能希望尝试以下内容。

def properly_format(line):
    nums = line.strip(' []\t').split() 
    spaces = '     '
    return spaces + nums[0] + spaces + nums[1] + spaces + nums[2]

lines = my_array_string.splitlines() #if your data is a multiline string
for line in lines:
    formatted_line = properly_format(line)
    # do something with formatted_line

编辑:忘了分割字符串。

答案 2 :(得分:0)

如果您不关心每个区块的长度,您可以这样做

for i in whateverYouArrayIsCalled:
    print str(i[0]) + "    " + str(i[1]) + "    " + str(i[2])

如果你想让所有元素都内联尝试

for i in whateverYouArrayIsCalled:
    print (str(i[0]) + "    ")[:20] + (str(i[1]) + "    ")[:20] + str(i[2])

其中20是每个块的长度

(对于2.7)

答案 3 :(得分:0)

我将假设数据数组保存在data.txt文件中,并且您希望将结果保存到fortran.txt中,然后:

    fortran_file = open('fortran.txt','w') # Open fortran.txt for writing

    with open('data.txt',r) as data_file: #Open data.txt for reading

            while True:
                line = data_file.readline()
                if not line: break # EOF
                result = line.strip('[]').split()
                result = "     " + "     ".join(result)
                fortran_file.write(result)

    fortran_file.close()

答案 4 :(得分:0)

尝试一下:

import numpy


numpy.set_printoptions(sign=' ')