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

Cách trích xuất số thực (floating point) từ văn bản bằng Python Regex

Dùng regex để tìm tất cả số thực (có dấu thập phân, có thể có dấu ±) trong text.

Ví dụ cơ bản

import re

text = "Sound Level: -11.7 db or 15.2 or 8 db"

# Pattern: optional sign + digits.digits OR digits
pattern = r'[-+]?\d*\.\d+|\d+'

matches = re.findall(pattern, text)
print(matches)
# ['-11.7', '15.2', '8']

Kết quả


['-11.7', '15.2', '8']

Phân tích Pattern

  • [-+]?: Dấu + hoặc - (tùy chọn).
  • \d*\.\d+: Số thực có dấu chấm (phần nguyên có thể rỗng: .5, hoặc có: 1.5).
  • |: HOẶC.
  • \d+: Số nguyên (fallback).

Pattern đầy đủ hơn (hỗ trợ khoa học, tránh false positive)


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

text = "Values: -11.7, +3.14, .5, 42, 1e-5, 2.5E+3, NaN, Inf"
print(re.findall(float_pattern, text))
# ['-11.7', '+3.14', '.5', '42', '1e-5', '2.5E+3']

Chuyển sang float để xử lý


numbers = [float(x) for x in re.findall(float_pattern, text)]
print(numbers)
# [-11.7, 3.14, 0.5, 42.0, 1e-05, 2500.0]

# Tính toán
print(f"Sum: {sum(numbers)}")
print(f"Max: {max(numbers)}")

Lưu ý

  • Pattern \d*\.\d+ khớp .5 nhưng KHÔNG khớp 5. (dấu chấm cuối). Thêm \d+\. nếu cần.
  • \d+ ở cuối pattern bắt số nguyên như '8' trong ví dụ.
  • Dùng re.finditer() nếu cần vị trí số trong text.