Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách trích xuất số (numbers) từ văn bản bằng Python Regex

Dùng \d (digit) hoặc \d+ (digit sequence) để extract numbers từ text.

1. Extract từng chữ số đơn lẻ

import re

text = '12345 abcdf 67'
# \d khớp 1 digit
print(re.findall(r'\d', text))
# ['1', '2', '3', '4', '5', '6', '7']

2. Extract nhóm số (số nguyên liên tiếp)


# \d+ khớp 1+ digits
print(re.findall(r'\d+', text))
# ['12345', '67']

Kết quả


['1', '2', '3', '4', '5', '6', '7']
['12345', '67']

3. Extract số thực (có dấu chấm)


text = "Price: $19.99, Quantity: 5, Discount: 10.5%"
# Pattern số thực hoặc nguyên
print(re.findall(r'\d+\.\d+|\d+', text))
# ['19.99', '5', '10.5']

4. Extract có dấu ±


text = "Temp: -5.5°C, +10.0°C, 25°C"
print(re.findall(r'[-+]?\d*\.\d+|\d+', text))
# ['-5.5', '+10.0', '25']

5. Convert sang int/float


# Tất cả số nguyên
ints = [int(x) for x in re.findall(r'\d+', text)]
# Tất cả số (thực + nguyên)
floats = [float(x) for x in re.findall(r'[-+]?\d*\.\d+|\d+', text)]

6. Counter - Đếm tần suất (built-in)


from collections import Counter

numbers = re.findall(r'\d+', '123 abc 456 123 789 456 123')
print(Counter(numbers))
# Counter({'123': 3, '456': 2, '789': 1})

Lưu ý

  • \d = [0-9] (ASCII digit). Với Unicode: re.ASCII flag hoặc module regex.
  • \d+ gom nhóm digits liên tiếp thành 1 match.
  • Để extract số trong context phức tạp (currency, percentage), cần pattern cụ thể hơn.