[英]read text file in block and convert to numpy array
我正在嘗試讀取帶有標簽的文本文件,然后將其轉換為 numpy 數組。 我的數據看起來像這樣
<header1>
0, 4, 7, 9
1, 2, 6, 8
2, 5, 7, 0
<header1>
.
.
.
<header2>
0, 6, 2, 10, 10, 8
1, 22, 56, 18, 7, 9
2, 57, 79, 09, 10, 1
<header2>
我寫了這樣的東西來提取標題中的數據
def read(infile):
with open('infile') as fp:
for line in re.findall('<header1>(.*?)<header1>', fp.read(), re.S):
print(line)
我的問題是如何將我所擁有的內容轉換為如下所示的 numpy 數組:
[[ 0 4 7 9]
[1 2 6 8 ]
[2 5 7 0 ]]
不是最好的優化方式,但你可以嘗試這樣的事情
def read(infile):
with open(infile) as fp:
for line in re.findall('<header[0-9]>(.*?)<header[0-9]>', fp.read(), re.S):
print(np.array([i.strip().split(', ') for i in line.split('\n') if i]) )
[['0' '4' '7' '9']
['1' '2' '6' '8']
['2' '5' '7' '0']]
[['0' '6' '2' '10' '10' '8']
['1' '22' '56' '18' '7' '9']
['2' '57' '79' '09' '10' '1']]
如果您可以收集“標題”之間的行塊,則可以使用標准csv
閱讀器創建一個數組:
In [569]: txt="""0, 4, 7, 9
...: 1, 2, 6, 8
...: 2, 5, 7, 0""".splitlines()
In [570]: txt
Out[570]: ['0, 4, 7, 9', '1, 2, 6, 8', '2, 5, 7, 0']
In [571]: data = np.genfromtxt(txt, delimiter=',', dtype=int)
In [572]: data
Out[572]:
array([[0, 4, 7, 9],
[1, 2, 6, 8],
[2, 5, 7, 0]])
genfromtxt
有比這個案例需要的更多的花里胡哨,但它很容易使用。 在這里,我只是給它一個字符串列表。
或者簡單地將行分解為可以轉換為整數的字符串:
In [586]: [s.split(',') for s in txt]
Out[586]: [['0', ' 4', ' 7', ' 9'], ['1', ' 2', ' 6', ' 8'], ['2', ' 5', ' 7', ' 0']]
In [587]: np.array([s.split(',') for s in txt],int)
Out[587]:
array([[0, 4, 7, 9],
[1, 2, 6, 8],
[2, 5, 7, 0]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.