【发布时间】:2015-06-26 01:17:02
【问题描述】:
有谁知道,我如何从我尝试使用numpy.genfromtxt 读取的文本文件中跳过括号
我的数据文件格式为
1.466 ((5.68 3.3 45.7)(4.5 6.7 9.5))
【问题讨论】:
标签: python numpy genfromtxt
有谁知道,我如何从我尝试使用numpy.genfromtxt 读取的文本文件中跳过括号
我的数据文件格式为
1.466 ((5.68 3.3 45.7)(4.5 6.7 9.5))
【问题讨论】:
标签: python numpy genfromtxt
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)
【讨论】: