从python中输入的值中提取电子邮件

时间:2017-10-08 12:27:59

标签: python loops

我的目标是:我需要让用户输入电子邮件的数量,然后启动for循环以注册输入的电子邮件。然后,电子邮件将根据'@ professor.com'和'@ student.com'进行隔离。这将被计为附加在列表中。以下就是我的尝试

email_count = int(input('how many emails you want'))
student_email_count = 0
professor_email_count = 0
student_email = '@student.com'
professor_email = '@professor.com'

for i in range(email_count):
   email_list = str(input('Enter the emails')
   if email_list.index(student_email):
       student_email_count = student_email_count + 1
   elif email_list.index(professor_email):
       professor_email_count = professor_email_count + 1

有人可以帮助缩短这一点并将其编写为专业解释,以供进一步参考吗?这里,缺少附加部分。那个人也可以通过一些亮点吗?

由于

2 个答案:

答案 0 :(得分:1)

您的迭代似乎一次只接受一封电子邮件;并执行email_count次。您可以使用这个简单的代码来计算学生和教授:

st = '@student.com'
prof = '@professor.com'

for i in range(email_count):
    email = str(input('Enter the email'))
    if st in email:
        student_email_count += 1
    elif prof in email:
        professor_email_count += 1
    else:
        print('invalid email domain')

如果您使用的是Python 2.7,则应将输入更改为raw_input

以下是代码的可扩展版本,使用defaultdict来支持无限域名。

email_count = int(input('how many emails you want'))
student_email_count = 0
professor_email_count = 0

from collections import defaultdict
domains = defaultdict(int)

for i in range(email_count):
    email = str(raw_input('Enter the email\n'))
    try:
        email_part = email.split('@')[1]
    except IndexError:
        print('invalid email syntax')
    else:
        domains[email_part] += 1

答案 1 :(得分:1)

prof_email_count, student_email_count = 0, 0

for i in range(int(input("Email count # "))):
    email = input("Email %s # " % (i+1)) 

    if email.endswith("@student.com"):  # str.endswith(s) checks whether `str` ends with s, returns boolean
        student_email_count += 1
    elif email.endswith("@professor.com"):
        prof_email_count += 1

代码的某种(某种程度上)缩短版本会是什么样子。主要区别在于我使用str.endswith(...)而不是str.index(...),我还删除了email_countstudent_emailprofessor_email变量似乎没有在上下文中的任何其他地方使用过。

编辑:

要回答您对可伸缩性的评论,您可以实现如下系统:

domains = {
    "student.com": 0,
    "professor.com": 0,
    "assistant.com": 0
}

for i in range(int(input("Email count # "))):
    email = input("Email %s # " % (i+1))

    try:
        domain = email.split('@')[1]
    except IndexError:
        print("No/invalid domain passed")
        continue

    if domain not in domains:
        print("Domain: %s, invalid." % domain)
        continue

    domains[domain] += 1

允许进一步扩展,因为您可以向domains字典添加更多域,并按domains[<domain>]

访问计数