无法使用正则表达式除去不需要的项

2024-09-29 23:31:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中创建了一个脚本,使用regular expression解析来自少数网站的电子邮件。我用来抓取电子邮件的模式是\w+@\w+\.{1}\w+,这在大多数情况下都有效。然而,当它遇到像8b4e078a51d04e0e9efdf470027f0ec1@sentry.wixpressSlice_1@2x.pnge.t.c这样的项目时,麻烦就来了。模式也抓住了它们,我想去掉它们

我试过:

import re
import requests

pattern = r'\w+@\w+\.{1}\w+'

urls = (  
    'https://rainforestfarms.org/contact',
    'https://www.auucvancouver.ca/',
    'http://www.bcla.bc.ca/',
    'http://www.palstudiotheatre.com/',
)

def get_email(link,pattern):
    res = requests.get(link)
    email = re.findall(pattern,res.text)
    if email:
        return link,email[0]
    else:
        return link

if __name__ == '__main__':
    for link in urls:
        print(get_email(link,pattern))

我得到的输出:

('https://rainforestfarms.org/contact', 'rainforestfarmsllc@gmail.com')
('https://www.auucvancouver.ca/', '8b4e078a51d04e0e9efdf470027f0ec1@sentry.wixpress')
('http://www.bcla.bc.ca/', 'Slice_1@2x.png')
('http://www.palstudiotheatre.com/', 'theatre@palvancouver.org')

我希望得到的产出:

('https://rainforestfarms.org/contact', 'rainforestfarmsllc@gmail.com')
https://www.auucvancouver.ca/
http://www.bcla.bc.ca/'
('http://www.palstudiotheatre.com/', 'theatre@palvancouver.org')

如何使用正则表达式清除不需要的项目


Tags: httpsorgcomhttpemailwwwlinkcontact
1条回答
网友
1楼 · 发布于 2024-09-29 23:31:36

这取决于你所说的“不想要的”是什么意思

定义它们的一种方法是使用允许的域后缀的白名单,例如“org”、“com”等

import re
import requests

pattern = r'\w+@\w+\.(?:com|org)'

urls = (
    'https://rainforestfarms.org/contact',
    'https://www.auucvancouver.ca/',
    'http://www.bcla.bc.ca/',
    'http://www.palstudiotheatre.com/',
)

def get_email(link,pattern):
    res = requests.get(link)
    email = re.findall(pattern, res.text)
    if email:
        return link, email[0]
    else:
        return link

for link in urls:
    print(get_email(link,pattern))

屈服

('https://rainforestfarms.org/contact', 'rainforestfarmsllc@gmail.com')
https://www.auucvancouver.ca/
http://www.bcla.bc.ca/
('http://www.palstudiotheatre.com/', 'theatre@palvancouver.org')

显然,您可以做更复杂的事情,例如黑名单或后缀的正则表达式模式

像往常一样,对于这类问题,我强烈建议使用regex101检查并理解您的正则表达式

相关问题 更多 >

    热门问题