有人知道吗,我如何从尝试使用numpy.genfromtxt
读取的文本文件中跳过括号我的数据文件的格式是
1.466 ((5.68 3.3 45.7)(4.5 6.7 9.5))
np.genfromttxt可以接受迭代器:
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 ]
或者,您可以使用(在Python 2中)str.translate
或(在Python 3中)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)