You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从txt文件中拆分用户名密码并校验密码合规性及解决代码报错

问题解决

核心错误原因

  • 遍历hasla列表的逻辑错误:for i in hasla中i本身就是每行的字符串内容,不是列表下标,使用hasla[i]会直接触发类型错误
  • 没有对每行内容做分割,直接用整行内容做校验,没有提取密码字段
  • 校验逻辑完全不符合需求:原代码判断整串为数字/大写/字母数字就返回False,和「至少包含一个对应字符」的要求完全不符
  • 多余的while True循环无实际作用,增加逻辑冗余

修复实现

方法1:正则实现(简洁高效)

import re

# 正则匹配规则:满足所有4项校验要求
# (?=.*[A-Z]):至少包含1个大写字母
# (?=.*\d):至少包含1个数字
# (?=.*[^A-Za-z0-9]):至少包含1个非字母数字的特殊符号
# .{9,}:长度大于8(至少9个字符)
pwd_rule = re.compile(r'^(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{9,}$')

for line in hasla:
    # 分割行内容,取第二个字段为密码
    line_parts = line.strip().split()
    if len(line_parts) < 2:
        # 格式异常行直接返回校验不通过
        print("False")
        continue
    password = line_parts[1]
    print("True" if pwd_rule.match(password) else "False")

方法2:纯字符串方法实现(无需正则依赖)

for line in hasla:
    line_parts = line.strip().split()
    if len(line_parts) < 2:
        print("False")
        continue
    password = line_parts[1]
    # 分别校验四个要求
    len_ok = len(password) > 8
    has_upper = any(c.isupper() for c in password)
    has_digit = any(c.isdigit() for c in password)
    has_special = any(not c.isalnum() for c in password)
    print("True" if all([len_ok, has_upper, has_digit, has_special]) else "False")

内容的提问来源于stack exchange,提问作者Ziggy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 18:54:00