Python numpy.genfromtxt

时间:2015-06-26 01:17:03

标签: python numpy genfromtxt

有谁知道,我如何跳过我尝试使用numpy.genfromtxt阅读的文本文件中的括号 我的数据文件格式为

1.466 ((5.68 3.3 45.7)(4.5 6.7 9.5))

1 个答案:

答案 0 :(得分:1)

np.genfromtxt可以接受迭代器:

import numpy as np
import re

with open('data', 'r') as f:
    lines = (line.replace('(',' ').replace(')',' ') for line in f)
    arr = np.genfromtxt(lines)
print(arr)

产量

[  1.466   5.68    3.3    45.7     4.5     6.7     9.5  ]

或者,您可以使用(在Python2中)str.translate或(在Python3中)bytes.translate方法,这样会快一点:

import numpy as np
import re

try:
    # Python2
    import string
    table = string.maketrans('()','  ')
except AttributeError:
    # Python3
    table = bytes.maketrans(b'()',b'  ')

with open('data', 'rb') as f:
    lines = (line.translate(table) for line in f)
    arr = np.genfromtxt(lines)
print(arr)