📅  最后修改于: 2023-12-03 15:27:14.156000             🧑  作者: Mango
在很多情况下,我们需要从给定的字符串中提取数字进行计算。例如,从一个字符串中提取商品价格并计算总价,或者从一个字符串中提取出预算数字并进行比较。在这种情况下,我们可以编写一个函数来提取字符串中的所有数字,并将它们加起来得到一个总和。
import re
def extract_numbers(text):
"""
从字符串中提取数字
"""
pattern = r'\d+'
numbers = re.findall(pattern, text)
return numbers
在这段代码中,我们定义了一个名为extract_numbers的函数,它接受一个字符串参数并返回一个字符串列表,这个列表包含了从原字符串中提取出的所有数字。我们使用re模块的findall函数来查找与给定模式匹配的所有子串。模式r'\d+'表示匹配一个或多个连续数字。
def sum_numbers(text):
"""
计算字符串中数字的总和
"""
numbers = extract_numbers(text)
if not numbers:
return 0
total = sum(int(n) for n in numbers)
return total
这段代码中,我们定义了一个名为sum_numbers的函数,它接受一个字符串参数并返回所有数字的总和。我们首先调用前面定义的extract_numbers函数来提取所有数字。如果没有数字,则函数返回0。否则,我们将所有数字转换为整数并使用sum函数求和。
text = 'The price of the product is $19.99 and the shipping cost is $5.50.'
total = sum_numbers(text)
print(f'Total cost: ${total:.2f}')
输出结果为:
Total cost: $25.49
通过正则表达式提取数字,并将其转换为整数进行加法操作,可以轻松地从字符串中提取出数值并进行计算。