如何检查字符串是否存在个性化错误?

时间:2019-07-18 18:10:27

标签: python

我正在尝试编写一个程序,在其中输入名称和姓氏,然后代码检查名称是否无效(下面的无效列表)。如果有任何无效,它会要求我再次说出名字,并向我显示所有无效的列表。 失效列表(我还将显示代码版本): -名称有数字 -名称带有符号 -名称中没有空格 -它有一个以上的空间 -名称之一太短或太长 -名称的第一个字母是空格 -名字的最后一个字母是空格

在这里我不能使用异常,因为这些不是代码错误。我已经用Ifs做到了,但是到了一定程度,只有很多Ifs才可行。

def has_digits(name):
    digits = any(c.isdigit() for c in name)
    if digits == True:
        return True
        print("Your name has digits.")
    else:
        return False


def has_symbols(name):
    symbols = any(not c.isalnum() and not c.isspace() for c in name)
    if symbols == True:
        return True
        print("Your name has symbols.")
    else:
        return False


def has_no_spaces(name):
    spaces = any(c.isspace() for c in name)
    if not spaces == True:
        return True
        print("You only gave me a name.")
    else:
        return False


def many_spaces(name):
    m_s = name.count(' ') > 1
    if m_s == True:
        return True
        print("Your name has more than one space.")
    else:
        return False


def unrealistic_length(name, surname):
    length= (float(len(name)) < 3 or float(len(name)) > 12) or float(len(surname)) < 5 or float(len(surname) > 15)
    if length == True:
        return True
        print("Your name has an unrealistic size.")
    else:
        return False


def first_space(name):
    f_s = name[0] == " "
    if f_s == True:
        return True
        print("The first letter of your name is a space.")
    else:
        return False


def last_space(name):
    l_s = name[-1] == " "
    if l_s == True:
        return True
        print("The last letter of your name is a space.")
    else:
        return False


name = "bruh browski"
namesplit = name.split(" ")
name1 = namesplit[0]
name2 = namesplit[1]

print(has_digits(name))
print(has_symbols(name))
print(has_no_spaces(name))
print(many_spaces(name))
print(unrealistic_length(name1, name2))
print(first_space(name))
print(last_space(name))

也许这些照片不应该放在自定义文件中。我不知道。我几乎可以确定要执行for循环是要走的路,但是我无法想象如何做到。

结果:

False
False
False
False
False
False
False

3 个答案:

答案 0 :(得分:3)

除非您可以用执行相同操作的其他方法替换它们,否则用于定义每次“无效”计数的方法将必须保留。但是您可以使用生成器表达式一次检查所有这些条件:

if any(is_invalid(name) for is_invalid in [
        has_digits, has_symbols, has_no_spaces, many_spaces, unrealistic_length, first_name, last_name
        ]):
    # then this string is invalid
# otherwise, all of those returned false, meaning the string is valid.

然后您可以使用该条件来确定何时停止询问用户,或者是否需要停止询问。

如果您不想单独定义所有这些功能,则也可以使用lambda来执行相同的操作。


作为旁注,在实际将其用于生产中以检查名称的有效性之前,我建议您先看看Falsehoods Programmers Believe about Names的列表。即使与您的用例无关,这也是一个有趣的阅读。

答案 1 :(得分:1)

您可以使用一个函数来调用所有其他函数并适当地处理它。

def master_verify(name):
    # Put all your verify functions in the list below.
    verify_funcs = [has_digits, has_symbols, has_no_spaces, many_spaces,
                    unrealistic_length, first_space, last_space]
    # It will return True if any your functions return True. In this case,
    # returning True means the name is invalid (matching your other 
    # function design). Returning False means the name is valid.
    return any(is_invalid(name) for is_invalid in verify_funcs)

由于您提到过要让程序查找任何名称错误并要求用户重试,因此我们可以编写一个循环来处理此问题。

def get_name():
    while True:
        # Loop until you get a good name
        name = input("Enter your name: ").strip()
        if master_verify(name): 
            # Remember, if True this means invalid
            print("Invalid name. Try again.")
            continue   # continue jumps to the top of a loop, skipping everything else.
        return name # Will only get here if the name is valid.

我还建议您在unrealistic_length函数中进行名称和姓氏的区分。

然后,您要做的就是

name = get_name()

# All of the validation has already happened.
print(f"The correct and validated name is: {name}")  

最后但并非最不重要的一点是,return之后的函数中的任何内容均不可访问。因此,您的许多print都不会发生。将print语句放在返回之前。

答案 2 :(得分:0)

好的。我已经设法自己做到了。我仍然认为有更好的方法可以做到这一点,但这就是我找到的方法。

errors_list = []
print("Hi. Tell me your first and last name.")
def choose_name(name):
    global fname
    global sname
    fname = ""
    sname = ""

    global errors_list

    try:
        no_letters = any(c.isalpha() for c in name)
        no_spaces = name.count(" ") == 0
        digits = any(c.isdigit() for c in name)
        symbols = any(not c.isalnum() and not c.isspace() for c in name)
        many_spaces = name.count(" ") > 1
        first_space = name[0] == " "
        last_space = name[-1] == " "

        if no_letters == False:
            errors_list.append("It has no letters")

        if no_spaces == True:
            errors_list.append("It has no spaces")
        else:
            namesplit = name.split(" ")
            fname = namesplit[0]
            sname = namesplit[1]
            pass

        if fname and sname is not "":
            bad_length = (float(len(fname)) < 3 or float(len(fname)) > 12) or float(len(sname)) < 4 or float(len(sname) > 15)
            if bad_length == True:
                errors_list.append("One of your names has an unrealistic size")
                pass
        else:
            bad_length = (float(len(name)) < 3 or float(len(name)) > 12)
            if bad_length == True:
                errors_list.append("It has an unrealistic size")
                pass

        if digits == True:
            errors_list.append("It has digits")
            pass

        if symbols == True:
            errors_list.append("It has symbols")
            pass

        if many_spaces == True:
            errors_list.append("It has more than one space")
            pass

        if first_space == True:
            errors_list.append("The first letter is a space")
            pass

        if last_space == True:
            errors_list.append("The last letter is a space")
            pass
    except IndexError:
        print("You must write something. Try again.")
        name = input("My name is ").title()
        choose_name(name)

name = input("My name is ").title()
choose_name(name)

while True:
    if len(errors_list) != 0:
        print("Your name has these errors:")
        for i in errors_list:
                print("     " + str(errors_list.index(i) + 1) + "- " + i + ".")
        print("Try again.")
        errors_list.clear()
        name = input("My name is ").title()
        choose_name(name)
    else:
        print("Nice to meet you, " + fname + " " + sname + ".")
        break

输入名称'----...'

时的结果
Hi. Tell me your first and last name.
My name is ----...    
Your name has these errors:
     1- It has no letters.
     2- It has symbols.
     3- It has more than one space.
     4- The last letter is a space.
Try again.
My name is