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

Tìm và thay thế văn bản trong file bằng Python (re.sub)

re.sub(pattern, repl, string) tìm tất cả match của pattern trong string và thay bằng repl. Trả về string mới (string immutable).

Cú pháp

re.sub(pattern, repl, string, count=0, flags=0)
  • count — số lần replace tối đa (0 = tất cả).
  • repl có thể là string hoặc function.

Ví dụ cơ bản

import re
result = re.sub(r'India', 'the World', 'TP is the most popular Tutorials site of India')
print(result)
# TP is the most popular Tutorials site of the World

Ví dụ nâng cao: replacement function

def repl_func(m):
    return m.group(0).upper()

re.sub(r'\d+', repl_func, 'Order 123 and 456')
# 'Order 123 AND 456' (wait, upper on match)

Áp dụng lên file

with open('file.txt', 'r') as f:
    content = f.read()
new_content = re.sub(r'old_pattern', 'new_text', content)
with open('file.txt', 'w') as f:
    f.write(new_content)