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

2024-04-20 04:56:26 发布

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

我的目标是:我需要要求用户输入电子邮件的数量,然后启动for循环来注册输入的电子邮件。然后,这些邮件将根据@教授网'和'@学生网'. 这将被视为附加在列表中。以下是我尝试过的

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

有没有人能帮你缩短这个时间,用专业的文字解释一下,以供进一步参考?在这里,附加部分不见了。有人也能从那里借点光吗?你知道吗

谢谢


Tags: 用户com目标forinput数量index电子邮件
2条回答

您的迭代似乎一次只接受一封电子邮件,并执行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')

如果您使用的是Python2.7,则应将输入更改为原始输入。你知道吗


下面是一个可扩展的代码版本,使用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
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>]的计数

相关问题 更多 >