前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 工具 字符串转numpy浮点数组的实现

python 工具 字符串转numpy浮点数组的实现

作者头像
砸漏
发布2020-11-05 10:45:57
2K0
发布2020-11-05 10:45:57
举报
文章被收录于专栏:恩蓝脚本恩蓝脚本

不同的数字之间使用 空格“ ”,“$”,”*”等隔开,支持带小数点的字符串

NumArray=str2num(LineString,comment=’#’)

将字符串中的所有非Double类型的字符全部替换成空格

以’#’开头直至行尾的内容被清空

返回一维numpy.array数组

代码语言:javascript
复制
import numpy
import scipy
def str2num(LineString,comment='#'):
 
  from io import StringIO as StringIO
  import re,numpy
 
  NumArray=numpy.empty([0],numpy.int16)
  NumStr=LineString.strip()
  #~ ignore comment string
  for cmt in comment:

    CmtRe=cmt+'.*$'
    NumStr=re.sub(CmtRe, " ", NumStr.strip(), count=0, flags=re.IGNORECASE)
 
  #~ delete all non-number characters,replaced by blankspace.
  NumStr=re.sub('[^0-9.e+-]', " ", NumStr, count=0, flags=re.IGNORECASE)
 
  #~ Remove incorrect combining-characters for double type.
  NumStr=re.sub('[.e+-](?=\s)', " ", NumStr.strip(), count=0, flags=re.IGNORECASE)
  NumStr=re.sub('[.e+-](?=\s)', " ", NumStr.strip(), count=0, flags=re.IGNORECASE)
  NumStr=re.sub('[e+-]$', " ", NumStr.strip(), count=0, flags=re.IGNORECASE)
  NumStr=re.sub('[e+-]$', " ", NumStr.strip(), count=0, flags=re.IGNORECASE)
 
  if len(NumStr.strip()) 0:
    StrIOds=StringIO(NumStr.strip())
    NumArray= numpy.genfromtxt(StrIOds)
 
  return NumArray


if __name__ == "__main__":
  str = input("Enter your input: ");
  donser=str2num(str)
  print(donser)

补充知识:Python 将numpy array由浮点型转换为整型

——使用numpy中的astype()方法可以实现,如:

以上这篇python 工具 字符串转numpy浮点数组的实现就是小编分享给大家的全部内容了,希望能给大家一个参考。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档