电子邮件检查器 - 为什么我的程序输出错误?

时间:2017-10-07 19:26:06

标签: python

import string
# Imported string to load dictionaries

d = dict.fromkeys(string.ascii_letters, 0)
ds = dict.fromkeys(string.digits, 0)
# 2 dictionaries imported, letters and numbers(digits)

f = {**d, **ds, ".":0}
# Merged both dictionaries together as well as "." as there was no specific 
dictionary.

while True:
   `email = input("Enter the name of the file (must be .txt file)")
    file = open(str(email), "r")
    for line in file:
        for i in line:
            if " " in line:
                print(line, "Space found")
                break

        if "@" not in line:
            print(line, "The email needs @")

        emailzero = line.split("@")
        if len(emailzero) < 2:
            print(line, "@ and a domain symbol is needed")
            continue

        if emailzero[0] == "":
            print(line, "You must enter a name")

        if emailzero[1] == "":
            print(line, "A Domain is needed")

        if "." in emailzero[0]:
            print(line, "Only alphabet and numbers")

        for i in emailzero[0]:
            if i not in f:
                print(line, "The email must have a valid character before @")
                break

        if "." not in emailzero[1]:
            print(line, "The domain needs to contain a .")

        for i in emailzero[1]:
            if i not in f:
                print(line, "The email must not contain any invalid characters in the domain.")
                break

所以这就是我的程序所做的。它接收一个电子邮件文件并逐个检查它是否有效。

问题是当我加载包含多封电子邮件的列表时,第一封电子邮件之后的电子邮件最终都会说“#34;电子邮件不得包含域中的任何无效字符。&#34;

有人可以告诉我为什么会发生这种情况以及如何解决它?

干杯,

2 个答案:

答案 0 :(得分:0)

从行if "@" not in line:开始,我想你需要再给出一些缩进。

答案 1 :(得分:0)

从文件中读取时,您的行将以某种换行符(\r\n\n)结束。如果你想逐行解析它,你应该确保去掉尾随和前导空格行:

emailzero = line.strip().split("@")

请参阅string.strip

其他提示:

  1. 关于此片段:
  2. 段:

    d = dict.fromkeys(string.ascii_letters, 0)
    ds = dict.fromkeys(string.digits, 0)
    # 2 dictionaries imported, letters and numbers(digits)
    
    f = {**d, **ds, ".":0}
    

    你可以将所有这些压缩成一个集合,如下所示:

    allowed_domain_chars = set(string.ascii_letters) | set(string.digits) | { '.' }
    
    1. 以不太可读的错误消息为代价,您可以将其压缩为regular expression

    2. 您的解析不接受所有有效的电子邮件地址(例如+左侧包含.@的电子邮件地址。像email_regex = re.compile(r'.+@.+\..+')这样的东西是一个简单的正则表达式,涵盖了大多数用例(给定the issues with validating email)。

相关问题