当前位置:首页 > 编程技术 > 正文

如何用函数提取单元格中的数字

如何用函数提取单元格中的数字

在Python中,可以使用正则表达式(regex)来提取单元格中的数字。以下是一个示例函数,它使用`re`模块来查找并返回字符串中的所有数字。```pythonimpo...

在Python中,可以使用正则表达式(regex)来提取单元格中的数字。以下是一个示例函数,它使用`re`模块来查找并返回字符串中的所有数字。

```python

import re

def extract_numbers(cell_content):

使用正则表达式匹配数字

numbers = re.findall(r'd+', cell_content)

将匹配到的数字字符串转换为整数列表

numbers = [int(num) for num in numbers]

return numbers

示例使用

cell_content = "Here are some numbers: 123, 456, and 789."

numbers = extract_numbers(cell_content)

print(numbers) 输出: [123, 456, 789]

```

这个函数`extract_numbers`接受一个字符串`cell_content`作为输入,该字符串代表单元格的内容。它使用`re.findall`来查找所有连续的数字序列,并将它们作为字符串列表返回。然后,它将这些字符串转换为整数列表并返回。

最新文章