# -*- 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)