文件in.txt存放

在文件in.txt中,存放有一组字符串 ,

每个字符串代表一个密码, 密码中不包含空格字符这些字符串用空格分隔,存放在文件的同一行内

对每个密码判断其强度等级

假设如下5个条件都满足,则为5级①包含大写字母

②包含小写字母

③包含数字字符

④包含有,除字母和数字以外的其它字符⑤字符串长度大于10

若满足以上条件中任意4个,则强度为4满足3个条件,强度为3

满足2个条件,强度为2

满足1个条件,强度为1

从文件in.txt中读取数据,

def password_strength(password):
    """判断密码强度"""
    count = 0
    # 包含大写字母
    if any(map(str.isupper, password)):
        count += 1
    # 包含小写字母
    if any(map(str.islower, password)):
        count += 1
    # 包含数字字符
    if any(map(str.isdigit, password)):
        count += 1
    # 包含有,除字母和数字以外的其它字符
    if any(not c.isalnum() for c in password):
        count += 1
    # 字符串长度大于10
    if len(password) > 10:
        count += 1
    return count

with open('in.txt', 'r') as f:
    for line in f:
        passwords = line.strip().split()
        for password in passwords:
            strength = password_strength(password)
            print(f'{password} strength: {strength}')


说明:首先定义了一个函数 password_strength,用于判断一个密码的强度等级。该函数接受一个字符串作为输入,依次判断是否包含大写字母、小写字母、数字字符、除字母和数字以外的其它字符和字符串长度是否大于10。通过计数器变量 count 统计满足条件的个数,并返回 count 的值。

之后 with 语句打开文件 in.txt,逐行读取数据。对于每一行数据,使用 strip() 方法去除空白字符,然后用 split() 方法分割出每个密码。对于每个密码,调用 password_strength 函数,输出密码及其强度等级。

遍历判断即可


with open('in.txt', 'r') as f_in:
passwords = f_in.readline().strip().split()

strengths = []
for password in passwords:
strength = 0
if any(c.isupper() for c in password):
strength += 1
if any(c.islower() for c in password):
strength += 1
if any(c.isdigit() for c in password):
strength += 1
if any(c.isalnum() == False for c in password):
strength += 1
if len(password) > 10:
strength += 1
strengths.append(strength)

with open('out.txt', 'w') as f_out:
for strength in strengths:
f_out.write(str(strength) + '\n')

如果有帮助,请点击一下采纳该答案~谢谢