首页 > 编程知识 正文

Python字符串提取邮箱

时间:2023-11-20 00:38:00 阅读:296373 作者:BWOD

本文旨在介绍如何使用Python提取字符串中的邮箱地址。

一、正则表达式提取邮箱

正则表达式是一种强大的模式匹配工具,可用于提取字符串中的特定模式。以下是使用正则表达式提取邮箱的示例代码:

import re

def extract_emails(text):
    pattern = r'b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}b'
    emails = re.findall(pattern, text)
    return emails

text = "John's email is john@example.com, and Mary's email is mary@example.com."
emails = extract_emails(text)
print(emails)

运行以上代码,将输出字符串中的所有邮箱地址。

二、字符串分割提取邮箱

除了正则表达式,我们还可以通过字符串分割方法来提取邮箱地址。以下是使用字符串分割提取邮箱的示例代码:

def extract_emails(text):
    emails = []
    words = text.split()
    for word in words:
        if '@' in word:
            emails.append(word)
    return emails

text = "John's email is john@example.com, and Mary's email is mary@example.com."
emails = extract_emails(text)
print(emails)

运行以上代码,同样可以提取字符串中的所有邮箱地址。

三、使用第三方库提取邮箱

除了使用Python内置模块,我们还可以使用第三方库来提取邮箱。例如,使用pandas库可以方便地从文本中提取邮箱地址。

import pandas as pd

def extract_emails(text):
    df = pd.DataFrame({'text': [text]})
    emails = df['text'].str.extractall(r'(b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}b)')[0].tolist()
    return emails

text = "John's email is john@example.com, and Mary's email is mary@example.com."
emails = extract_emails(text)
print(emails)

运行以上代码,同样可以提取字符串中的所有邮箱地址。

四、总结

本文介绍了如何使用Python提取字符串中的邮箱地址。通过正则表达式、字符串分割和第三方库,我们可以轻松地从文本中提取出需要的邮箱信息。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。