在 Python 中从字符串中提取数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26825729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:03:28  来源:igfitidea点击:

Extract Number from String in Python

pythonstringpython-3.x

提问by Umair

I am new to Pythonand I have a String, I want to extract the numbers from the string. For example:

我是新手Python,我有一个字符串,我想从字符串中提取数字。例如:

str1 = "3158 reviews"
print (re.findall('\d+', str1 ))

Output is ['4', '3']

输出是 ['4', '3']

I want to get 3158only, as an Integer preferably, not as List.

我只想得到3158,最好是整数,而不是列表。

采纳答案by Vishnu Upadhyay

You can filterthe string by digitsusing str.isdigitmethod,

您可以使用方法filter数字字符串str.isdigit

>>> int(filter(str.isdigit, str1))
3158

回答by 6502

If the format is that simple (a space separates the number from the rest) then

如果格式那么简单(一个空格将数字与其余数字分开)那么

int(str1.split()[0])

would do it

会做的

回答by hellobenallan

Your regex looks correct. Are you sure you haven't made a mistake with the variable names? In your code above you mixup total_hotel_reviews_stringand str.

您的正则表达式看起来正确。你确定你没有弄错变量名吗?在你的代码你上面的mixuptotal_hotel_reviews_stringstr

>>> import re
>>> s = "3158 reviews"
>>> 
>>> print(re.findall("\d+", s))
['3158']

回答by Irshad Bhat

This code works fine. There is definitely some other problem:

这段代码工作正常。肯定还有其他问题:

>>> str1 = "3158 reviews"
>>> print (re.findall('\d+', str1 ))
['3158']

回答by M.Danilchenko

There may be a little problem with code from Vishnu's answer. If there is no digits in the string it will return ValueError. Here is my suggestion avoid this:

毗湿奴的回答中的代码可能有一点问题。如果字符串中没有数字,它将返回 ValueError。这是我的建议,避免这种情况:

>>> digit = lambda x: int(filter(str.isdigit, x) or 0)
>>> digit('3158 reviews')
3158
>>> digit('reviews')
0

回答by Yang Qi

My answer does not require any additional libraries, and it's easy to understand. But you have to notice that if there's more than one number inside a string, my code will concatenate them together.

我的答案不需要任何额外的库,而且很容易理解。但是您必须注意,如果字符串中有多个数字,我的代码会将它们连接在一起。

def search_number_string(string):
    index_list = []
    del index_list[:]
    for i, x in enumerate(string):
        if x.isdigit() == True:
            index_list.append(i)
    start = index_list[0]
    end = index_list[-1] + 1
    number = string[start:end]
    return number

回答by Eugene Yarmash

To extract a single number from a string you can use re.search(), which returns the first match (or None):

要从字符串中提取单个数字,您可以使用re.search(),它返回第一个匹配项(或None):

>>> import re
>>> string = '3158 reviews'
>>> int(re.search(r'\d+', string).group(0))
3158

回答by Bernard

IntVar = int("".join(filter(str.isdigit, StringVar)))

回答by thund

Above solutions seem to assume integers. Here's a minor modification to allow decimals:

以上解决方案似乎假设整数。这是一个允许小数的小修改:

num = float("".join(filter(lambda d: str.isdigit(d) or d == '.', inputString)

(Doesn't account for - sign, and assumes any period is properly placed in digit string, not just some english-language period lying around. It's not built to be indestructible, but worked for my data case.)

(不考虑 - 符号,并假设任何句号都正确放置在数字字符串中,而不仅仅是一些英文句号。它不是为了坚不可摧,而是适用于我的数据案例。)

回答by Ayush Singh

Use this, THIS IS FOR EXTRACTING NUMBER FROM STRING IN GENERAL.

使用这个,这通常用于从字符串中提取数字。

To get all the numeric occurences.

获取所有出现的数字。

*split function to convert string to list and then the list comprehension which can help us iterating through the list and is digit function helps to get the digit out of a string.

*split 函数将字符串转换为列表,然后列表理解可以帮助我们遍历列表,并且是数字函数有助于从字符串中获取数字。

getting number from string

从字符串中获取数字

use list comprehension+isdigit()

使用列表理解+isdigit()

test_string = "i have four ballons for 2 kids"

print("The original string : "+ test_string)


# list comprehension + isdigit() +split()

res = [int(i) for i in test_string.split() if i.isdigit()]
print("The numbers list is : "+ str(res))

To extract numeric values from a string in python

在python中从字符串中提取数值

*Find list of all integer numbers in string separated by lower case characters using re.findall(expression,string)method.

*使用re.findall(expression,string)方法查找以小写字符分隔的字符串中所有整数的列表。

*Convert each number in form of string into decimal number and then find max of it.

*将字符串形式的每个数字转换为十进制数,然后找到它的最大值。

import re 
 def extractMax(input):

# get a list of all numbers separated by lower case characters

 numbers = re.findall('\d+',input) 



# \d+ is a regular expression which means one or more digit

number = map(int,numbers)
print max(numbers)
if __name__=="__main__":
input = 'sting'
extractMax(input)