Python:文本过滤处理器

文章目录

    • 1.使用筛选器验证电子邮件地址

1.使用筛选器验证电子邮件地址

You are given an integer N followed by N email addresses. Your task is to print a list containing only valid email addresses in lexicographical order.

Valid email addresses must follow these rules:

  • It must have the [email protected] format type.
  • The username can only contain letters, digits, dashes and underscores.
  • The website name can only have letters and digits.
  • The maximum length of the extension is 3.

输入

3
[email protected]
[email protected]
[email protected]

输出

[‘[email protected]’, ‘[email protected]’, ‘[email protected]’]

程序样例

def fun(s):
	#your code here
    # return True if s is a valid email, else return False

def filter_mail(emails):
    return list(filter(fun, emails))

if __name__ == '__main__':
    n = int(input())
    emails = []
    for _ in range(n):
        emails.append(input())

filtered_emails = filter_mail(emails)
filtered_emails.sort()
print(filtered_emails)

代码
分离出username,website,extension,并根据rules判断各部分是否符合要求

def fun(s):
    try:
        username, url = s.split("@")
        website, extension = url.split(".")
    except ValueError:
        return False
    
    if not username.replace("-", "").replace("_", "").isalnum():
        return False
    elif not website.isalnum():
        return False
    elif len(extension) > 3:
        return False
    else:
        return True

你可能感兴趣的:(Python:文本过滤处理器)