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

Trích xuất số từ chuỗi bằng Regular Expression (re) trong Python

Trích xuất số từ văn bản là nhu cầu phổ biến trong data analytics. Module re (regular expression) giải quyết tốt bài toán này.

1. Chỉ lấy chữ số (bỏ dấu chấm, dấu âm)

import re

text = "Go to 13.8 miles and then -4.112 miles."
numbers = re.findall(r'\d+', text)
print(numbers)  # ['13', '8', '4', '112']

\d+: 1 hoặc nhiều chữ số liên tiếp.

2. Lấy cả dấu chấm thập phân và dấu ±

import re

text = "Go to 13.8 miles and then -4.112 miles."
# Pattern: dấu ± tùy chọn, chữ số, dấu chấm tùy chọn, chữ số
numbers = re.findall(r'[-+]?\d*\.?\d+', text)
print(numbers)  # ['13.8', '-4.112']

3. Pattern mạnh mẽ hơn (hỗ trợ scientific notation)

import re

pattern = r'[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?'

text = "Values: 3.14, -2.5e10, +100, .5, 42, -0.001"
numbers = re.findall(pattern, text)
print(numbers)
# ['3.14', '-2.5e10', '+100', '.5', '42', '-0.001']

4. Chuyển đổi sang float

import re

text = "Temp: -5.5°C, 23.4°C, 100°C"
nums = [float(x) for x in re.findall(r'[-+]?\d*\.?\d+', text)]
print(nums)        # [-5.5, 23.4, 100.0]
print(sum(nums))   # 117.9

Bảng pattern thường dùng

PatternKhớp vớiVí dụ
\d+Số nguyên dương123
[-+]?\d+Số nguyên có dấu-45, +12
\d+\.\d+Số thực có phần thập phân3.14
[-+]?\d*\.?\d+Số thực tổng quát.5, 3., -2.5
[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?Khoa học (scientific)1e-5, -2.5E+3

Kết luận

Dùng re.findall() với pattern phù hợp. Pattern [-+]?\d*\.?\d+ đủ cho hầu hết trường hợp thực tế.