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

โปรแกรม Python สกัดอีเมลจากไฟล์ข้อความ URL

ที่นี่เราใช้แพ็กเกจ regular expression (re) สำหรับสกัดอีเมลจากไฟล์ข้อความ URL กำหนดให้มีไฟล์ข้อความ URL ใช้แพ็กเกจ regular expression กำหนดรูปแบบของอีเมล แล้วใช้ฟังก์ชัน findall() เพื่อตรวจสอบข้อความที่ตรงกับรูปแบบนี้

ตัวอย่างข้อมูลนำเข้าและผลลัพธ์

Input text = "Please contact us at contact@tutorialspoint.com for further information." + 
             " You can also give feedback at feedback@tutorialspoint.com"

Output: ['contact@tutorialspoint.com', 'feedback@tutorialspoint.com']

โค้ดตัวอย่าง

import re

my_text = ("Please contact us at contact@tutorialspoint.com for further information." +
           " You can also give feedback at feedback@tutorialspoint.com")

# รูปแบบ regex สำหรับอีเมล
my_emails = re.findall(r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+", my_text)

print(my_emails)

ผลลัพธ์

['contact@tutorialspoint.com', 'feedback@tutorialspoint.com']

คำอธิบาย Regular Expression

  • [a-z0-9\.\-+_]+ - ตัวอักษร a-z, ตัวเลข 0-9, จุด, ขีดลบ, บวก, ขีดล่าง (1 ตัวขึ้นไป) สำหรับส่วน local-part
  • @ - สัญลักษณ์ @
  • [a-z0-9\.\-+_]+ - โดเมนเนม (รูปแบบเดียวกัน)
  • \. - จุดก่อน TLD
  • [a-z]+ - Top-level domain (com, org, net, ฯลฯ)

หมายเหตุ: รูปแบบนี้เป็นรูปแบบง่าย สำหรับการใช้งานจริงอาจต้องใช้ regex ที่ซับซ้อนกว่านี้เพื่อรองรับอีเมลทุกรูปแบบตาม RFC 5322