如何读取文本文件中的数组列表字符串并提取数组值?
读取文本中numpy数组字符串的解决方案
错误原因
运行代码时出现name 'float32' is not defined,是因为eval执行时默认命名空间里没有numpy的array和float32对象,无法识别字符串里的这些标识。
可行解决方法
方法1:给eval注入numpy命名空间
直接将numpy的相关对象传入eval的全局命名空间,让它能解析字符串里的numpy语法:
import numpy as np datPath = "./" # 替换为你的实际路径 with open(datPath+'histo1.txt', 'r') as file: hist1 = np.array(eval(file.read(), {"array": np.array, "float32": np.float32})) print(hist1)
方法2:简化字符串后解析
如果只需要数组数值,可以先去掉字符串里的dtype=float32标识,再用eval解析:
import numpy as np datPath = "./" with open(datPath+'histo1.txt', 'r') as file: content = file.read().replace(", dtype=float32", "") hist1 = np.array(eval(content)) # 如需指定类型,可后续转换 hist1 = hist1.astype(np.float32) print(hist1)
方法3:用ast模块安全解析(推荐)
eval存在安全风险,若文本内容不可信,使用ast.literal_eval进行安全解析:
import numpy as np import ast datPath = "./" with open(datPath+'histo1.txt', 'r') as file: content = file.read() # 替换numpy数组格式为纯列表格式 content = content.replace("array(", "").replace(")", "").replace(", dtype=float32", "") num_list = ast.literal_eval(content) hist1 = np.array(num_list, dtype=np.float32) print(hist1)
内容的提问来源于stack exchange,提问作者bsekirarski
相关产品推荐
相关产品推荐

