0
有誰知道,我怎麼會從文本文件跳過括號我嘗試使用numpy.genfromtxt
我的數據文件格式Python的numpy.genfromtxt
1.466 ((5.68 3.3 45.7)(4.5 6.7 9.5))
有誰知道,我怎麼會從文本文件跳過括號我嘗試使用numpy.genfromtxt
我的數據文件格式Python的numpy.genfromtxt
1.466 ((5.68 3.3 45.7)(4.5 6.7 9.5))
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)
由於HappyLeapSecond !!這工作! –