Python,numpy,字符串分解(来自Abaqus AFXComTableKeyword.getValues()的字符串)

时间:2013-05-06 13:05:30

标签: python string numpy

getValues()方法从AFXComTableKeyword方法返回一个字符串,如:

test = "('mat_huehne_2008', '0.125', '24.0'),('', '', '-24.0'),('', '', '41.0')"+\
       ",('', '', '-41.0'),('', '', ''),('', '', ''),('', '', ''),('','', ''),"+\
       "('', '', ''),('', '', ''),('', '', ''),('', '', ''),('', '', ''),"+\
       "('', '', ''),('', '', ''),('', '', ''),('', '', ''),('', '', ''),"+\
       "('', '', ''),('', '', ''),('', '', ''),('', '', ''),('', '', ''),"+\
       "('', '', ''),('', '', ''),('', '', ''),('', '', ''),('', '', ''),"+\
       "('', '', ''),('', '', ''),('', '', ''),('', '', ''),('', '', ''),"+\
       "('', '', ''),('', '', ''),('', '', ''),('', '', ''),('', '', ''),"+\
       "('', '', ''),('', '', '')"

最后,我们需要numpy.array shape=(40,3),对于这种情况,我们需要:

 test = [['mat_huehne_2008', '0.125',  '24.0'],
         [               '',      '', '-24.0'],
         ... and so on ... ]

有没有人知道在Python / Numpy中执行此操作的快捷方式?

1 个答案:

答案 0 :(得分:3)

我使用ast将字符串评估为元组。那很容易:

>>> import ast
>>> import numpy as np
>>> np.array(ast.literal_eval(test))
array([['mat_huehne_2008', '0.125', '24.0'],
       ['', '', '-24.0'],
       ['', '', '41.0'],
       ['', '', '-41.0'],
       ...