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

作者:未名亚柳 时间:2023-07-15 20:37:16 

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

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

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

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

返回一维numpy.array数组

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


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浮点数组的实现

来源:https://www.cnblogs.com/dzzy/p/9399487.html

标签:python,字符串,numpy,浮点数组
0
投稿

猜你喜欢

  • Python实现查找数组中任意第k大的数字算法示例

    2022-04-26 22:10:46
  • Django实现文件上传下载

    2022-03-17 18:42:48
  • Python趣味挑战之教你用pygame画进度条

    2022-08-13 15:02:49
  • MySql 5.6.14 Win32位免安装解压缩版配置教程

    2024-01-13 01:27:44
  • PHP的mysqli_stmt_init()函数讲解

    2023-06-08 05:04:51
  • MySQL的表级锁,行级锁,排它锁和共享锁

    2024-01-28 15:44:22
  • mysql代码执行结构实例分析【顺序、分支、循环结构】

    2024-01-21 23:18:40
  • Django REST Framework序列化外键获取外键的值方法

    2022-02-23 16:03:14
  • Mootools 1.2教程(3)——数组使用简介

    2008-11-17 20:16:00
  • Python使用tkinter模块实现GUI界面的学生信息管理系统流程分步详解

    2022-04-06 18:09:53
  • 详解Python中@staticmethod和@classmethod区别及使用示例代码

    2023-06-03 12:17:20
  • 网页版权的正确写法

    2007-09-22 09:13:00
  • Django如何实现内容缓存示例详解

    2022-02-23 15:33:01
  • Golang空接口与类型断言的实现

    2024-04-27 15:39:21
  • CKeditor富文本编辑器使用技巧之添加自定义插件的方法

    2024-04-18 09:52:24
  • PyTorch线性回归和逻辑回归实战示例

    2021-09-12 17:50:57
  • mysql 获取时间方式

    2024-01-20 03:26:14
  • SQL中DATEADD和DATEDIFF的用法示例介绍

    2024-01-27 16:57:58
  • vue前端项目打包成Docker镜像并运行的实现

    2023-07-02 17:05:55
  • Nodejs中调用系统命令、Shell脚本和Python脚本的方法和实例

    2024-05-13 09:29:17
  • asp之家 网络编程 m.aspxhome.com