用python和numpy处理数据次数比较多,写了几个小函数,可以方便地读写数据:
# -*- coding: utf-8 -*-
#----------------------------------------------------------------------
# filename:gettxtdata.py
#功能:读取字符串和文件中的数值数据(浮点数)
#主要提供类似matlab中的dlmread和dlmwrite函数
#同时提供loadtxtdata和savetxtdata函数
#data: 2013-1-10
#author:吴徐平
#----------------------------------------------------------------------
import numpy
#----------------------------------------------------------------------
def stringtodoublearray(string):
"""
#将字符串中的所有非double类型的字符全部替换成空格
#以'#'开头注释直至行尾,都被清空
#返回一维numpy.array数组
"""
from stringio import stringio
import re
dataarray=numpy.empty([0],numpy.float64)
if len(string.strip())>0:
#清空注释行,都是以'#'开头子字符
doublestring=re.sub('#.*$', " ", string, count=0, flags=re.ignorecase)
#删除非数字字符
doublestring=re.sub('[^0-9.e+-]', " ", doublestring, count=0, flags=re.ignorecase)
#去掉不正确的数字格式(代码重复是有必要的)
doublestring=re.sub('[.e+-](?=\s)', " ", doublestring, count=0, flags=re.ignorecase)
doublestring=re.sub('[.e+-](?=\s)', " ", doublestring, count=0, flags=re.ignorecase)
doublestring=re.sub('[e+-]$', " ", doublestring, count=0, flags=re.ignorecase)
doublestring=re.sub('[e+-]$', " ", doublestring, count=0, flags=re.ignorecase)
#去掉首尾空格
doublestring=doublestring.strip()
if len(doublestring)>0:
striods=stringio(doublestring)
dataarray= numpy.genfromtxt(striods)
return dataarray
#----------------------------------------------------------------------
def getdoublelistfromstring(string):
"""
#使用换行符分割字符串
#将字符串中的所有非double类型的字符全部替换成空格
#以'#'开头注释直至行尾,都被清空
#将每一行转换成numpy.array数组
#返回numpy.array数组的列表
"""
from stringio import stringio
import re
doublelist=[]
stringlist=string.split('\n')#使用换行符分割字符串
for line in stringlist:
if len(line.strip())>0:
#清空注释行,都是以'#'开头子字符
doublestring=re.sub('#.*$', " ", line, count=0, flags=re.ignorecase)
#删除非数字字符
doublestring=re.sub('[^0-9.e+-]', " ", doublestring, count=0, flags=re.ignorecase)
#去掉不正确的数字格式(代码重复是有必要的)
doublestring=re.sub('[.e+-](?=\s)', " ", doublestring, count=0, flags=re.ignorecase)
doublestring=re.sub('[.e+-](?=\s)', " ", doublestring, count=0, flags=re.ignorecase)
doublestring=re.sub('[e+-]$', " ", doublestring, count=0, flags=re.ignorecase)
doublestring=re.sub('[e+-]$', " ", doublestring, count=0, flags=re.ignorecase)
#去掉首尾空格
doublestring=doublestring.strip()
if len(doublestring)>0:
striods=stringio(doublestring)
doublelist.append(numpy.genfromtxt(striods))
return doublelist
#----------------------------------------------------------------------
def getdoublelistfromfile(filename):
"""
#将文本文件中的所有double类型的字符全部替换成numpy.array数组
#每一行都是numpy.array数组
##返回numpy.array数组的列表
#注意:返回列表的每个元素又都是一个numpy.array数组
#注意:返回列表的每个元素(或文件每行)可以包含不同多个数的数字
"""
file=open(filename, 'r')
read_file = file.read()
file.close()
doublelist=getdoublelistfromstring(read_file)
return doublelist
def dlmread(filename,dtype=numpy.float64):
"""
#load data from txt-file.
#分隔符默认是:";",",",空格类 (包括\t)等等
#以#开头的被认为是注释,不会被读取
#return value:二维数值数组(numpy.ndarray)
#对文本中数据的排列格式要求最低,且容许出现注释字符,智能化程度最高,但速度较慢
"""
doublelist=getdoublelistfromfile(filename)
dlsize=[]#每一行数组的大小
for dl in doublelist:
dlsize.append(dl.size)
mincolumnsize=min(dlsize)#数组的最大列数
maxcolumnsize=max(dlsize)#数组的最小列数
#数组创建和赋值
doublearray=numpy.empty([len(doublelist),mincolumnsize],dtype=dtype)
row=range(0,len(doublelist))
colum=range(0,mincolumnsize)
for i in row:
for j in colum:
doublearray[i][j]=doublelist[i][j]
return doublearray
#----------------------------------------------------------------------
def loadtxtdata(filename,delimiter=""):
"""
#load data from txt-file with delimiter.
#分隔符默认是:";",",",空格类 (包括\t)和自定义的delimiter等
#return value: 二维数值数组(numpy.ndarray)
#对文本中数据的排列格式要求较高,且不容许出现注释字符,智能化程度较低,但速度较快
"""
from stringio import stringio
import re
file_handle=open(filename,'r')
linesall=file_handle.read()#读入字符串
file_handle.close()
delimiterall=delimiter+",;"#分隔符
spacestring=" "#空格
for rchar in delimiterall:
linesall=linesall.replace(rchar,spacestring)
return numpy.genfromtxt(stringio(linesall))
#----------------------------------------------------------------------
def savetxtdata(filename, x, fmt='%.8e', delimiter=' ', newline='\n'):
"""
save data to txt-file.
"""
numpy.savetxt(filename, x, fmt=fmt, delimiter=delimiter, newline=newline)
return true
#----------------------------------------------------------------------
def dlmwrite(filename, x, fmt='%.8e', delimiter=' ', newline='\n'):
"""
save data to txt-file.
"""
numpy.savetxt(filename, x, fmt=fmt, delimiter=delimiter, newline=newline)
return true
#----------------------------------------------------------------------
#测试程序
#----------------------------------------------------------------------
if __name__ == '__main__':
#生成随机数
data=numpy.random.randn(3,4)
filename='d:/x.txt'
#写入文件
dlmwrite(filename,data)
x=getdoublelistfromfile(filename)
print(x)
print(dlmread(filename))
y=stringtodoublearray('79l890joj')
print(y)
z=loadtxtdata(filename)
print(z)
我只在python2.7中试过,如果要在python3.x中使用,可自行测试.