如何在Python中高效读取含方括号的.txt矩阵文件?
高效读取带方括号的txt矩阵解决方案
这里提供三种高效的方法解决你的问题,同时注意你的数据是浮点数,直接指定dtype='i'会丢失精度,建议先读取为浮点数再按需转换。
方法一:字符串预处理 + numpy.fromstring
这种方法直接处理文件内容,移除干扰的方括号后快速加载,适合大矩阵场景:
import numpy as np with open("testing789.txt", "r") as f: content = f.read() # 移除所有方括号,解析为一维数组后重塑维度 matrix = np.fromstring(content.replace('[', '').replace(']', ''), dtype=np.float64, sep=' ') matrix = matrix.reshape(10, 8) # 根据你的矩阵维度调整 # 若确实需要整数类型,可转换 # matrix = matrix.astype(np.int32) print(matrix)
方法二:用ast模块解析为Python列表再转numpy数组
利用ast.literal_eval安全解析字符串为原生列表,代码简洁可读性强:
import numpy as np import ast with open("testing789.txt", "r") as f: content = f.read() # 解析为Python列表后转numpy数组 py_list = ast.literal_eval(content) matrix = np.array(py_list, dtype=np.float64) # 按需转换为整数 # matrix = matrix.astype(np.int32) print(matrix)
方法三:预处理每行后使用np.loadtxt
如果你更习惯使用np.loadtxt,可以先清理每行的方括号:
import numpy as np def clean_line(line): return line.strip().replace('[', '').replace(']', '') with open("testing789.txt", "r") as f: # 过滤空行并清理每行内容 cleaned_content = [clean_line(line) for line in f if line.strip()] matrix = np.loadtxt(cleaned_content, dtype=np.float64) # 按需转换为整数 # matrix = matrix.astype(np.int32) print(matrix)
注意:你的原始数据包含浮点数(比如0.26263508),直接用
dtype='i'会导致转换错误或精度丢失,建议先以浮点数读取,再通过astype转换为整数类型。
内容的提问来源于stack exchange,提问作者Rashid Abramov
相关产品推荐
相关产品推荐

