我正在嘗試讀取.txt
檔案。但是,輸出是字串,我沒有得到實際的陣列。我在下面介紹當前和預期的輸出。
import numpy as np
with open('Test.txt') as f:
A = f.readlines()
print(A)
當前輸出為
['[array([[1.7],\n', ' [2.8],\n', ' [3.9],\n', ' [5.2]])]']
預期的輸出是
[array([[1.7],
[2.8],
[3.9],
[5.2]])]
uj5u.com熱心網友回復:
通過使用regex
和ast.literal_eval:
import re
import ast
#Your output
s = ['[array([[1.7],\n', ' [2.8],\n', ' [3.9],\n', ' [5.2]])]']
#Join them
s = ' '.join(s)
#Find the list in string by regex
s = re.findall("\((\[[\w\W]*\])\)",s)
#Convert string to list
ast.literal_eval(s[0])
輸出:
[[1.7], [2.8], [3.9], [5.2]]
通過使用regex
和eval
:
import re
#Your output
s = ['[array([[1.7],\n', ' [2.8],\n', ' [3.9],\n', ' [5.2]])]']
#Join them
s = ' '.join(s)
#Find the list in string by regex
s = re.findall("\((\[[\w\W]*\])\)",s)
#Convert string to list
eval(s[0])
輸出:
[[1.7], [2.8], [3.9], [5.2]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/507406.html