从Python的字符串列表中返回电子邮件地址的函数

我需要创建一个函数,该函数从字符串列表中返回电子邮件地址。我已使用以下代码成功完成了此任务:

def myfunction(bigstring):
    str = ' '.join(bigstring)
    my_string = str
    str1 = re.findall(r'[\w\.-]+@[\w\.-]+',my_string)
    return str1

但是,当我运行以下示例时:

emails = ['John Kennedy <jk123@gmail.com> or <johnk123@hotmail.com>','Adam Hartley <ah123@yahoo.com>','Ben Saunders <benji@live.co.uk>']
myfunction(emails)

我得到输出:

['jk123@gmail.com','johnk123@hotmail.com','ah123@yahoo.com','benji@live.co.uk']

但是我想要以下输出,但是我不确定如何在不弄乱我的代码的情况下这样做:

[['jk123@gmail.com',johnk123@hotmail.com'],['ah123@yahoo.com'],['benji@live.co.uk']]

我需要返回列表中的列表,如期望的输出所示。

inuyasha7 回答:从Python的字符串列表中返回电子邮件地址的函数

您不需要加入包含字符串的电子邮件的初始数组。

<version>
,

提取每个列表项中的电子邮件:

import re

emails = ['John Kennedy <jk123@gmail.com> or <johnk123@hotmail.com>','Adam Hartley <ah123@yahoo.com>','Ben Saunders <benji@live.co.uk>']
def myfunction(bigstring):
    result = []
    for s in bigstring:
        result.append(re.findall(r'[\w.-]+@[\w.-]+',s))
    return result

print(myfunction(emails))
# => [['jk123@gmail.com','johnk123@hotmail.com'],['ah123@yahoo.com'],['benji@live.co.uk']]

请参见Python demo

实际上,bigstring在这里是一个不好的名字,因为它是一个列表。考虑重命名为my_list之类的东西。

对于正则表达式,您无需在字符类中转义点。

,

不要将整个字符串连接到函数中,并像这样通过迭代逐一传递字符串

import re
def myfunction(bigstring):
    return  re.findall(r'[\w\.-]+@[\w\.-]+',bigstring)

emails = ['John Kennedy <jk123@gmail.com> or <johnk123@hotmail.com>','Ben Saunders <benji@live.co.uk>']


output = []
for emailstring in emails:
    output.append((myfunction(emailstring)))
print(output)

使用列表理解

output = [ myfunction(email) for email in emails ]
print(output)

使用地图

print(map(myfunction,emails))

输出

[['jk123@gmail.com',['benji@live.co.uk']]
,
def myfunction(bigstring):
    #str = ' '.join(bigstring)
    #my_string = str
    str1 = re.findall(r'[\w\.-]+@[\w\.-]+',bigstring)
    return str1

import re
output=[]
emails = ['John Kennedy <jk123@gmail.com> or <johnk123@hotmail.com>','Ben Saunders <benji@live.co.uk>']
for item in emails:
    output.append(myfunction(item))

print(output)
,
    def myfunction(bstr):
        #str = ' '.join(bstr)
        #my_string = str
        str1 = re.findall(r'[\w\.-]+@[\w\.-]+',bstr)
        return str1
    import re
    output=[]
    emails = ['John Kennedy <jk123@gmail.com> or <johnk123@hotmail.com>','Adam 
              Hartley <ah123@yahoo.com>','Ben Saunders <benji@live.co.uk>']
     for item in emails:
        output.append(myfunction(item))
本文链接:https://www.f2er.com/3144751.html

大家都在问