我在txt文件上写了一些数组,像这样的数组:
[ 121.6 114.7 117.9 122.1 114.8 121.2 115.3 116.3 116. 121.
115.3 120.8 114.4 115.5 116.9 127.7 119.4 118.1 116.3 115.3
119.5 115.7 116.1 114.3 119. 116. 114.2 340.8 114.6 116.6
118.5 114.1 121.3 120.6 116.3]
和另一个类似的数组
[[122.54227 ]
[123.13425 ]
[122.04907 ]
[122.696365]
[123.1821 ]
[121.818115]
[123.11479 ]
[121.908745]
[122.193954]
[121.94495 ]
[122.76871 ]
[121.7559 ]
[122.98235 ]
[121.78393 ]
[122.06499 ]
[122.05317 ]
[123.91927 ]
[122.679565]
[123.07596 ]]
是否可以使用读取文件返回此数组形式?
答案 0 :(得分:0)
首先,像这样读取并存储文件内容:
with open('input.txt', 'r') as myfile:
filearray = myfile.read()
如果将filearray
的内容格式化为有效的python列表(例如[1, 2, 3, 4]
或[[1], [2], [3], [4]]
),则可以直接使用literal_eval
from the ast
module:
outputlist = literal_eval(filearray)
print(type(outputlist),outputlist)
输出:
<class 'list'> [1, 2, 3, 4]
如果文件中的列表值不是逗号分隔的,则可以使用正则表达式将其格式化为有效列表(演示:https://regex101.com/r/4aO40h/2):
filearray = re.sub(r"(?<!\[)[,\s]+(?!\s*])(?=.*\w)",", ", filearray)
outputlist = literal_eval(filearray)
print(type(outputlist),outputlist)
输出:
<class 'list'> [1, 2, 3, 4]