Jos*_*son 5 python string floating-point scientific-notation
我试图从文本文件中的行中提取科学数字.就像是
例:
str = 'Name of value 1.111E-11 Next Name 444.4'
Run Code Online (Sandbox Code Playgroud)
结果:
[1.111E-11, 444.4]
Run Code Online (Sandbox Code Playgroud)
我在其他帖子中尝试过解决方案,但它看起来只适用于整数(可能)
>>> [int(s) for s in str.split() if s.isdigit()]
[]
Run Code Online (Sandbox Code Playgroud)
float()可以工作,但每次使用字符串时都会出错.
>>> float(str.split()[3])
1.111E-11
>>> float(str.split()[2])
ValueError: could not convert string to float: value
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的帮助!!
这可以用正则表达式完成:
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
Run Code Online (Sandbox Code Playgroud)
输出:
[1.111e-11, 444.4]
Run Code Online (Sandbox Code Playgroud)
请注意,我在上面编写的模式取决于小数点左侧至少存在一位。
编辑:
这是我发现对学习如何编写正则表达式模式有用的教程和参考。
由于您要求解释正则表达式模式:
'-?\ *[0-9]+\.?[0-9]*(?:[Ee]\ *-?\ *[0-9]+)?'
Run Code Online (Sandbox Code Playgroud)
一次一件:
-? 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
Run Code Online (Sandbox Code Playgroud)
注意:\ d是[0-9]的快捷方式,但我习惯于使用[0-9]。
您始终可以只使用for循环和try-except语句。
>>> string = 'Name of value 1.111E-11 Next Name 444.4'
>>> final_list = []
>>> for elem in string.split():
try:
final_list.append(float(elem))
except ValueError:
pass
>>> final_list
[1.111e-11, 444.4]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6313 次 |
| 最近记录: |