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

วิธีค้นหาและแทนที่ข้อความใน Python

ปัญหา

คุณต้องการค้นหาและแทนที่รูปแบบข้อความในสตริง

กรณีง่าย: ใช้ str.replace()

ถ้ารูปแบบเป็น literal ธรรมดา ใช้ str.replace() เป็นวิธีที่เหมาะสมที่สุด

ตัวอย่าง

def sample():
    yield 'Is'
    yield 'USA'
    yield 'Colder'
    yield 'Than'
    yield 'Canada?'
text = ' '.join(sample())
print(f"Output \n {text}")

ผลลัพธ์: Is USA Colder Than Canada?

ค้นหาข้อความ

# exact match
print(f"Output \n {text == 'USA'}")
# False

# ใช้ string methods
print(f"Output \n {text.startswith('Is')}")  # True
print(f"Output \n {text.endswith('Canada?')}")  # True
print(f"Output \n {text.find('USA')}")  # 3 (index)

กรณีซับซ้อน: ใช้ Regular Expressions (re module)


# ตัวอย่างวันที่ format dd/mm/yyyy
date1 = '22/10/2020'
# ตรวจสอบว่ามีตัวเลขมากกว่า 1 หลัก
import re
if re.match(r'\d+/\d+/\d+', date1):
    print('yes')
else:
    print('no')
# yes

แทนที่ข้อความ

กรณีง่าย: str.replace()

print(f"Output \n {text.replace('USA', 'Australia')}")

ผลลัพธ์: Is Australia Colder Than Canada?

กรณีซับซ้อน: re.sub()

อาร์กิวเมนต์แรกคือ pattern ที่จะ match, อาร์กิวเมนต์ที่สองคือ replacement pattern


import re
sentence = 'Date is 22/11/2020. Tommorow is 23/11/2020.'
# แปลง dd/mm/yyyy เป็น yyyy-dd-mm
# \3, \1, \2 หมายถึง capture group ลำดับที่ 3, 1, 2
replaced_text = re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', sentence)
print(f"Output \n {replaced_text}")

ผลลัพธ์: Date is 2020-22-11. Tommorow is 2020-23-11.

คอมไพล์ pattern ก่อนเพื่อประสิทธิภาพ


pattern = re.compile(r'(\d+)/(\d+)/(\d+)')
replaced_pattern = pattern.sub(r'\3-\1-\2', sentence)
print(f"Output \n {replaced_pattern}")

re.subn() คืนค่าจำนวนการแทนที่ด้วย


output, count = pattern.subn(r'\3-\1-\2', sentence)
print(f"Output \n {output}")
print(f"Output \n {count}")

ผลลัพธ์: 2 (แทนที่ 2 ครั้ง)