Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การค้นหาและแทนที่ข้อความในไฟล์ด้วย Python (re.sub)

โมดูล re มีฟังก์ชัน re.sub() สำหรับค้นหา pattern และแทนที่ด้วย substring ใหม่ หาไม่เจอ → คืนสตริงเดิม

ไวยากรณ์

re.sub(pattern, repl, string, count=0, flags=0)
  • pattern - regex pattern
  • repl - สตริงแทนที่ (หรือฟังก์ชัน)
  • string - สตริงต้นทาง
  • count - จำนวนครั้งสูงสุดที่แทนที่ (0 = ทั้งหมด)
  • flags - regex flags

ตัวอย่างพื้นฐาน

>> 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

ตัวอย่างขั้นสูง: ใช้ฟังก์ชันเป็น Replacement

>> def double_digits(match):
...     return str(int(match.group()) * 2)

>>> re.sub(r'\d+', double_digits, 'I have 2 apples and 10 oranges')
'I have 4 apples and 20 oranges'

การใช้งานกับไฟล์

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

ฟังก์ชันที่เกี่ยวข้อง

  • re.subn() - คืนค่า (new_string, number_of_subs)
  • re.escape() - Escape อักขระพิเศษในสตริงให้ใช้เป็น literal pattern