簡體   English   中英

如何在Python中從字符串中提取數字?

[英]How to extract a number from a string in Python?

如何從字符串中提取數字以進行操作? 該數字可以是intfloat 例如,如果字符串是"flour, 100, grams""flour, 100.5, grams"則提取數字100100.5

代碼

string  = "flour, 100, grams"
numbers = [int(x) for x in string.split(",")]
print(numbers)

輸出

Traceback (most recent call last):
  File "/Users/lewis/Documents/extracting numbers.py", line 2, in <module>
    numbers = [int(x) for x in string.split(",")]
 File "/Users/lewis/Documents/extracting numbers.py", line 2, in <listcomp>
   numbers = [int(x) for x in string.split(",")]
ValueError: invalid literal for int() with base 10: 'flour'

給定字符串的結構,當您使用str.split將字符串拆分為三個字符串的列表時,您應該只采用以下三個元素之一:

>>> s = "flour, 100, grams"
>>> s.split(",")
['flour', ' 100', ' grams']
>>> s.split(",")[1] # index the middle element (Python is zero-based)
' 100'

然后,您可以使用float將字符串轉換為數字:

>>> float(s.split(",")[1])
100.0

如果不確定字符串的結構,可以使用re (正則表達式)提取數字並map以將它們全部轉換:

>>> import re
>>> map(float, re.findall(r"""\d+ # one or more digits
                              (?: # followed by...
                                  \. # a decimal point 
                                  \d+ # and another set of one or more digits
                              )? # zero or one times""",
                          "Numbers like 1.1, 2, 34 and 15.16.",
                          re.VERBOSE))
[1.1, 2.0, 34.0, 15.16]

您是否嘗試過除鑄型周圍的塊以外的其他塊,這將扔掉細粉,但保持100

string = 'flour, 100, grams'
numbers = []

    for i in string.split(','):
    try:
        print int(i)
        numbers.append(i)
    except: pass

給自己寫一個轉換函數,就像下面的轉換函數一樣,它首先嘗試將其參數轉換為int ,然后轉換為float ,然后轉換為complex (只是擴展示例)。 如果您希望獲取/保留最適合輸入的類型,則嘗試轉換的順序很重要,因為int將成功轉換為float ,反之則不然,因此您需要嘗試將輸入轉換為float首先是int

def convert_to_number(n):
    candidate_types = (int, float, complex)
    for t in candidate_types:
        try:
            return t(str(n))
        except ValueError:
#            pass
            print "{!r} is not {}".format(n, t)    # comment out if not debugging
    else:
        raise ValueError('{!r} can not be converted to any of: {}'.format(n, candidate_types))

>>> s = "flour, 100, grams"
>>> n = convert_to_number(s.split(',')[1])
>>> type(n)
<type 'int'>
>>> n
100

>>> s = "flour, 100.123, grams"
>>> n = convert_to_number(s.split(',')[1])
' 100.123' is not <type 'int'>
>>> type(n)
<type 'float'>
>>> n
100.123

>>> n = convert_to_number('100+20j')
'100+20j' is not <type 'int'>
'100+20j' is not <type 'float'>
>>> type(n)
<type 'complex'>
>>> n
(100+20j)

>>> n = convert_to_number('one')
'one' is not <type 'int'>
'one' is not <type 'float'>
'one' is not <type 'complex'>
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/tmp/ctn.py", line 10, in convert_to_number
    raise ValueError('{!r} can not be converted to any of: {}'.format(n, candidate_types))
ValueError: 'one' can not be converted to any of: (<type 'int'>, <type 'float'>, <type 'complex'>)

您可以使用正則表達式根據jonrsharpe的答案從輸入的每一行中提取數字字段。

有一個非常簡單和最佳的方法來從字符串中提取數字。 您可以使用以下代碼從字符串中提取N個數字。

-獲取整數-

import re
s = 'flour, 100, grams, 200HC'
print(re.findall('\d+', s))

-獲取浮點數-

import re
map(float, re.findall(r"""\d+ # one or more digits
                          (?: # followed by...
                              \. # a decimal point 
                              \d+ # and another set of one or more digits
                          )? # zero or one times""",
                      "Numbers like 1.1, 2, 34 and 15.16.",
                      re.VERBOSE))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM