【发布时间】:2020-02-21 23:17:12
【问题描述】:
我正在制作一个程序,用户必须创建一个至少 8 个字符长的密码,包含至少一个数字、至少一个小写字母和至少一个大写字母。困难的部分是密码不能包含瑞典语词典中的任何单词。我已将字典中的每个单词都存储在一个文本文件中。无论如何我可以检查密码是否包含我从字典中制作的列表中的单词?
def main():
print("Write a password with at least 8 characters",
"which contains at least 1 digit,",
"\nat least 1 uppercase letter, at least one lowercase character",
"and at least 1 special character")
password = input("The password may not contain any word from the dictionary:")
if checkAllow(password) == True:
print("\nYour password is allowed")
else:
print("\nYour password is not allowed")
main()
# This function checks if the password is allowed
def checkAllow(password):
words = open("dictionary.txt", "r")
wordlist = words.readlines()
specialChar = ['!', '@', '#', '¤', '£', '$', '%', '€', '&', '/', '{', '(',
'[', ')', ']', '=', '}', '+', '?', '"', '¨', '^', '¨', '*',
',', ';', '.', ':', '-', '_', '<', '>', '|', '§', '½']
if len(password) >= 8 and any(char.isdigit() for char in password):
if any(char.isupper() for char in password) and any(char.islower() for char in password):
if any(char in specialChar for char in password):
# Below I try to check if the password contains a word from the dictionary.
if any(word in password for word in wordlist) == False:
return True
else:
return False
【问题讨论】:
-
if substring in longstring:会告诉您子字符串是否出现在长字符串中的任何位置。 -
顺便说一句,
if boolean_expression == boolean: return boolean是一个典型的错误 -
您应该使用上下文管理器来处理文件对象。此外,变量和函数名称应遵循
lower_case_with_underscores样式。 -
另外,使用set类型而不是list来执行检查,会快很多。