이메일 주소를 추출하려면 Python에서 정규 표현식을 사용할 수 있습니다.
이메일 주소의 패턴은 보통 account@domain.com와 같은 형태를 가지며, 일반적으로 문자, 숫자, 특수 문자 및 마침표를 포함합니다.
아래는 텍스트 파일에서 이메일 주소를 추출하는 간단한 Python 코드 예제입니다.
# -*- coding: utf-8 -*-
import re
import os
#--------------------------
# 설정
#--------------------------
#directory_path = 'E:/Work'
output_file_path = 'E:/Work/email_export.txt'
#--------------------------
# email 추출하여 저장하기
#--------------------------
def extract_emails_from_files(directory):
# 이메일 주소를 저장할 리스트
emails = []
# 디렉터리 내의 파일 목록을 가져옴
file_list = os.listdir(directory)
# 각 파일에 대해 처리
for (root, directories, files) in os.walk(directory_path):
for file_name in files:
# 텍스트 파일인 경우에만 처리
if file_name.endswith('.txt'):
file_path = os.path.join(root, file_name)
print(file_path)
with open(file_path, 'r', errors='ignore') as file:
# 파일 내용을 읽어옴
contents = file.read()
# 이메일 주소를 정규식으로 추출
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b'
#emails += re.findall(pattern, content)
matches = re.findall(pattern, contents)
emails.extend(matches)
return emails
#--------------------------
# 결과 저장
#--------------------------
def save_email_to_file(emails, output_file_path):
with open(output_file_path, 'w') as output_file:
for email in emails:
output_file.write(email + '\n')
#print(email)
#--------------------------
# Main
#--------------------------
if __name__ == "__main__":
emails = extract_emails_from_files(directory_path)
save_email_to_file(emails, output_file_path)
이 코드는 주어진 텍스트 파일에서 이메일 주소를 찾아내고, 그 주소들을 리스트로 반환합니다.
그리고 이메일 주소 리스트 save_email_to_file 함수를 사용하여 출력파일로 저장합니다.
정규 표현식은 email_pattern 변수에 저장되며, 주어진 패턴은 이메일 주소의 기본 형식을 매칭하는 것입니다.
댓글