python - 从字符串中提取科学数字

标签 python string floating-point scientific-notation

我正在尝试从文本文件中的行中提取科学数字。有点像

例子:

str = 'Name of value 1.111E-11   Next Name 444.4'

结果:

[1.111E-11, 444.4]

我在其他帖子中尝试过解决方案,但看起来它只适用于整数(可能)

>>> [int(s) for s in str.split() if s.isdigit()]
[]

float() 可以工作,但每次使用字符串时我都会出错。

>>> float(str.split()[3])
1.111E-11
>>> float(str.split()[2])
ValueError: could not convert string to float: value

在此先感谢您的帮助!

最佳答案

这可以用正则表达式来完成:

import re
s = 'Name of value 1.111E-11   Next Name 444.4'
match_number = re.compile('-?\ *[0-9]+\.?[0-9]*(?:[Ee]\ *-?\ *[0-9]+)?')
final_list = [float(x) for x in re.findall(match_number, s)]
print final_list

输出:

[1.111e-11, 444.4]

请注意,我上面写的模式取决于小数点左边至少有一位数字。

编辑:

这是 a tutorial and reference我发现这对学习如何编写正则表达式模式很有帮助。

由于您要求解释正则表达式模式:

'-?\ *[0-9]+\.?[0-9]*(?:[Ee]\ *-?\ *[0-9]+)?'

一次一个:

-?        optionally matches a negative sign (zero or one negative signs)
\ *       matches any number of spaces (to allow for formatting variations like - 2.3 or -2.3)
[0-9]+    matches one or more digits
\.?       optionally matches a period (zero or one periods)
[0-9]*    matches any number of digits, including zero
(?: ... ) groups an expression, but without forming a "capturing group" (look it up)
[Ee]      matches either "e" or "E"
\ *       matches any number of spaces (to allow for formats like 2.3E5 or 2.3E 5)
-?        optionally matches a negative sign
\ *       matches any number of spaces
[0-9]+    matches one or more digits
?         makes the entire non-capturing group optional (to allow for the presence or absence of the exponent - 3000 or 3E3

注意:\d 是 [0-9] 的快捷方式,但我只是习惯使用 [0-9]。

关于python - 从字符串中提取科学数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18152597/

相关文章:

python - Django 类型错误未提供异常

python - 数据读取-csv

python - xyzc 值数组,查找第 3 列是否有任何 c 值等于 1 或不为零的行

c - 我的程序替换链表中所有节点中的所有字符串数据类型

time - 埃尔姆的时间不精确,是吗?

C# float 无限循环

python - 将列表的每个元素传递给在 Python 中采用多个参数的函数?

c - 返回字符串的函数不工作 - 段错误

python - 根据字符串长度填充列表的空列表

python - 我的 Python 代码的输出说明