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

การแบ่งสตริงด้วย Line Break หรือ Period ด้วย Python Regex

ใช้ re.findall() กับ Regex pattern ที่จับคู่ข้อความระหว่าง Period (.) และ Newline (\n)

ตัวอย่าง

import re
s = """Hi. It's nice meeting you. My name is Jason."""
result = re.findall(r'[^\s\.][^\.\n]+', s)
print(result)

ผลลัพธ์

["Hi", "It's nice meeting you", "My name is Jason"]

คำอธิบาย Pattern [^\s\.][^\.\n]+

  • [^\s\.] - อักขระแรก: ไม่ใช่ whitespace และไม่ใช่จุด (เริ่มต้นคำ)
  • [^\.\n]+ - ต่อมา: อักขระที่ไม่ใช่จุดและไม่ใช่ newline 1+ ตัว

วิธีที่ง่ายกว่า: ใช้ split()

>> import re
>>> re.split(r'[.\n]\s*', s.strip('.'))
["Hi", "It's nice meeting you", "My name is Jason", '']

# หรือ str.split() แบบง่าย
>>> [part.strip() for part in s.split('.') if part.strip()]
["Hi", "It's nice meeting you", "My name is Jason"]

แนะนำ: ใช้ str.split() หรือ re.split() สำหรับงานแบ่งสตริงง่ายๆ คงใช้ findall() เมื่อต้องการจับคู่ pattern ที่ซับซ้อน