亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從字符串中提取浮點數

如何從字符串中提取浮點數

滄海一幻覺 2019-07-03 16:30:14
如何從字符串中提取浮點數我有許多類似于Current Level: 13.4 db.我只想提取浮點數。我說的是浮點,而不是小數,因為它有時是完整的。RegEx能做到這一點嗎?還是有更好的方法?
查看完整描述

3 回答

?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

如果浮點數總是用十進制表示法表示,如下所示

>>> import re>>> re.findall("\d+\.\d+", "Current Level: 13.4 db.")['13.4']

可能就夠了。

一個更有力的版本是:

>>> re.findall(r"[-+]?\d*\.\d+|\d+", "Current Level: -13.2 db or 14.2 or 3")['-13.2', '14.2', '3']

如果您想驗證用戶輸入,也可以通過直接到它來檢查浮點數:

user_input = "Current Level: 1e100 db"for token in user_input.split():
    try:
        # if this succeeds, you have your (first) float
        print float(token), "is a float"
    except ValueError:
        print token, "is something else"# => Would print ...## Current is something else# Level: 
        is something else# 1e+100 is a float# db is something else


查看完整回答
反對 回復 2019-07-03
?
ABOUTYOU

TA貢獻1812條經驗 獲得超5個贊

您可能會嘗試這樣的方法,它涵蓋了所有的基礎,包括在數字之后不依賴空格:

>>> import re>>> numeric_const_pattern = r"""
...     [-+]? # optional sign
...     (?:
...         (?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc
...         |
...         (?: \d+ \.? ) # 1. 12. 123. etc 1 12 123 etc
...     )
...     # followed by optional exponent part if desired
...     (?: [Ee] [+-]? \d+ ) ?
...     """>>> rx = re.compile(numeric_const_pattern, re.VERBOSE)>>> rx.findall(".1 .12 9.1 98.1 1. 12. 1 12")
['.1', '.12', '9.1', '98.1', '1.', '12.', '1', '12']>>> rx.findall("-1 +1 2e9 +2E+09 -2e-9")['-1', '+1', '2e9', '+2E+09', '-2e-9']
>>> rx.findall("current level: -2.03e+99db")['-2.03e+99']>>>

為方便復制粘貼:

numeric_const_pattern = '[-+]? (?: (?: \d* \. \d+ ) | (?: \d+ \.? ) )(?: [Ee] [+-]? \d+ ) ?'
rx = re.compile(numeric_const_pattern, re.VERBOSE)rx.findall("Some example: Jr. it. was .23 between 2.3 and 42.31 seconds")


查看完整回答
反對 回復 2019-07-03
?
GCT1015

TA貢獻1827條經驗 獲得超4個贊

Python文檔有一個包含+/-和指數表示法的答案

scanf() Token      Regular Expression%e, %E, %f, %g     [-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?%i                
 [-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)

此正則表達式不支持使用逗號作為整個部分和小數部分之間的分隔字符(3,14159)的國際格式。在這種情況下,替換所有\.帶著[.,]在上面的浮動正則表達式中。

                        Regular ExpressionInternational float     [-+]?(\d+([.,]\d*)?|[.,]\d+)([eE][-+]?\d+)?


查看完整回答
反對 回復 2019-07-03
  • 3 回答
  • 0 關注
  • 1531 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號