python读取浮点数和读取文本文件示例
时间:2022-10-31 16:03:38
从文本文件中读入浮点数据,是最常见的任务之一,python没有scanf这样的输入函数,但我们可以利用正规表达式从读入的字符串中提取出浮点数
import re
fp = open('c:/1.txt', 'r')
s = fp.readline()
print(s)
aList = re.findall('([-+]?\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?',s) #使用正规表达式搜索字符串
print(aList)
for ss in aList:
print(ss[0]+ss[2])
aNum = float((ss[0]+ss[2]))
print(aNum)
fp.close()
文件内容:
12.540 56.00 1.2e2 -1.2E2 3.0e-2 4e+3
输出结果:
12.540 56.00 1.2e2 -1.2E2 3.0e-2 4e+3
[('12.540', '.540', ''), ('56.00', '.00', ''), ('1.2', '.2', 'e2'), ('-1.2', '.2', 'E2'), ('3.0', '.0', 'e-2'), ('4', '', 'e+3')]
12.540
12.54
56.00
56.0
1.2e2
120.0
-1.2E2
-120.0
3.0e-2
0.03
4e+3
4000.0
注解:
按行读入文本文件,利用正规表达式找出字符串中的浮点数,使用float()函数将字符串转换为浮点数
标签:python,浮点数,文本文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
SQL SERVER 与ACCESS、EXCEL的数据转换方法分享
2012-02-25 20:17:22
asp用正则过滤html标签
2008-01-19 16:34:00
Pytorch maxpool的ceil_mode用法
2023-03-20 13:28:05
Thinking XML: 创建 XML 的好建议
2008-05-29 11:25:00
交互设计实用指南系列(11)—减少记忆负担
2010-03-29 13:12:00
![](https://img.aspxhome.com/file/UploadPic/20103/29/t1za0vxjlexxxxxxxx-569-268-29s.jpg)
Python中类型检查的详细介绍
2022-08-18 16:51:47
![](https://img.aspxhome.com/file/2023/7/70017_0s.jpg)
在python里创建一个任务(Task)实例
2023-09-12 23:24:16
跟老齐学Python之for循环语句
2021-12-22 04:52:50
Python解析nginx日志文件
2023-09-07 18:22:09
php发送get、post请求的6种方法简明总结
2023-11-14 12:59:43
Session.TimeOut的最大取值是1440,超出会报错
2011-03-31 11:19:00
用色彩打造专业的视觉效果
2010-09-25 19:04:00
![](https://img.aspxhome.com/file/UploadPic/20109/25/01-36s.jpg)
IE8网页显示不正常 用”兼容性视图”搞定
2009-03-28 11:13:00
![](https://img.aspxhome.com/file/UploadPic/20093/28/u2973p2t78d16163f3306dt20090319092333-31s.png)
Python采用raw_input读取输入值的方法
2021-09-08 03:19:05
Python图像处理之图像的缩放、旋转与翻转实现方法示例
2023-03-09 11:25:20
![](https://img.aspxhome.com/file/2023/4/93794_0s.jpg)
Python利用Pillow(PIL)库实现验证码图片的全过程
2022-05-18 21:27:47
![](https://img.aspxhome.com/file/2023/7/81457_0s.png)
SQL Server中链接服务器将替代远程服务器
2009-06-15 11:03:00
tensorflow 2.1.0 安装与实战教程(CASIA FACE v5)
2022-06-12 08:41:23
![](https://img.aspxhome.com/file/2023/8/92208_0s.jpg)
详解Python装饰器
2023-11-12 12:40:06
教你一步步利用python实现贪吃蛇游戏
2023-09-21 13:23:27
![](https://img.aspxhome.com/file/2023/0/107810_0s.png)