正则获取文本 中整数 python
时间: 2024-05-14 12:16:48 浏览: 11
您可以使用 Python 中的正则表达式来获取文本中的整数。以下是一个示例代码:
```
import re
text = "I have 10 apples and 20 bananas."
numbers = re.findall(r'\d+', text)
print(numbers)
```
输出是:
```
['10', '20']
```
该代码使用了 Python 的 re 模块,通过正则表达式 `'\d+'` 匹配所有的数字,然后通过 `findall()` 方法将这些数字提取出来。
相关问题
python读取文本中的数字
可以使用Python中的正则表达式模块re来匹配文本中的数字。具体实现可以参考以下代码:
```python
import re
text = "The price of the product is $9.99, and the quantity is 10."
# 匹配文本中的数字
numbers = re.findall(r'\d+\.\d+|\d+', text)
# 输出匹配到的数字
print(numbers)
```
运行结果为:
```
['9.99', '10']
```
代码中,我们使用re.findall()函数匹配文本中的数字。正则表达式r'\d+\.\d+|\d+'表示匹配小数或整数。其中,\d+表示至少匹配一个数字,\.\d+表示匹配小数点后面的数字,|表示或者,整个正则表达式匹配小数或整数。最后,使用print()函数输出匹配到的数字。
PYTHON提取文本行中数字部分
可以使用正则表达式来提取文本行中的数字部分。具体来说,使用`re.findall()`函数来匹配数字,然后将其转换为整数或浮点数。
下面是一个示例代码:
```python
import re
text = "The price is $12.35 per unit"
numbers = re.findall(r'\d+\.\d+|\d+', text)
# 匹配浮点数或整数
# \d+ 匹配一位或多位数字
# \. 匹配小数点
# \d+ 匹配一位或多位数字
for num in numbers:
print(float(num))
```
输出结果:
```
12.35
```
这段代码首先使用正则表达式匹配文本中的数字部分,然后将其转换为浮点数。如果文本中有多个数字,它们将被打印出来。