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

Python凯撒密码加密代码问题求助:输入验证与需求适配

凯撒密码加密工具的问题修复与优化

问题梳理

你需要实现的是读取指定文本文件、加密后写入目标文件的凯撒密码工具,要求保留标点符号并做输入验证。当前代码存在以下核心问题:

  • 输入文本验证用了isalpha(),导致无法接受空格和标点符号
  • 没有按需求读取文件,而是手动输入文本,不符合功能要求
  • 凯撒密码只处理小写字母,大写字母会乱码,且未跳过标点/空格

修改后的完整代码

import string

def validate_input_text(text):
    # 验证文本仅包含英文字母、标点和空格
    allowed_chars = set(string.ascii_letters + string.punctuation + " ")
    return all(char in allowed_chars for char in text)

def validate_key(key):
    # 验证密钥是整数
    try:
        return int(key)
    except ValueError:
        return None

def caesar_cipher(text, key):
    encrypted_chars = []
    key = key % 26  # 确保密钥在0-25范围内
    for char in text:
        if char.islower():
            # 处理小写字母
            new_ord = ord(char) + key
            encrypted_chars.append(chr(new_ord) if new_ord <= ord('z') else chr(new_ord - 26))
        elif char.isupper():
            # 处理大写字母
            new_ord = ord(char) + key
            encrypted_chars.append(chr(new_ord) if new_ord <= ord('Z') else chr(new_ord - 26))
        else:
            # 标点、空格直接保留
            encrypted_chars.append(char)
    return ''.join(encrypted_chars)

def encrypt_file(input_path, output_path, key):
    # 读取输入文件
    try:
        with open(input_path, 'r', encoding='utf-8') as f:
            text = f.read()
    except FileNotFoundError:
        print(f"错误:输入文件 {input_path} 不存在")
        return False
    
    # 验证文件内容
    if not validate_input_text(text):
        print("错误:文件内容包含不允许的字符(仅允许英文字母、标点和空格)")
        return False
    
    # 加密并写入目标文件
    encrypted_text = caesar_cipher(text, key)
    try:
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(encrypted_text)
        print(f"加密完成,结果已写入 {output_path}")
        return True
    except Exception as e:
        print(f"写入文件时出错:{e}")
        return False

# 主程序逻辑
if __name__ == "__main__":
    # 获取并验证输入文件路径
    while True:
        input_file = input("请输入待加密文件的路径:")
        if input_file.strip():
            break
        print("请输入有效的文件路径")
    
    # 获取并验证输出文件路径
    while True:
        output_file = input("请输入加密后文件的保存路径:")
        if output_file.strip():
            break
        print("请输入有效的文件路径")
    
    # 获取并验证密钥
    while True:
        key_input = input("请输入加密密钥(整数):")
        key = validate_key(key_input)
        if key is not None:
            break
        print("请输入有效的整数密钥")
    
    # 执行加密
    encrypt_file(input_file, output_file, key)

关键改进说明

  • 输入验证修复:用string.ascii_letters + string.punctuation + " "定义允许的字符集合,遍历文本检查每个字符是否在集合内,替代原来的isalpha()
  • 适配文件读写需求:新增encrypt_file函数,接收输入/输出路径,负责文件读写和加密流程,完全符合需求
  • 密码逻辑完善:区分大小写字母分别处理,非字母字符直接保留,避免乱码
  • 增强鲁棒性:添加文件存在性检查、写入异常捕获,避免程序崩溃
  • 代码结构优化:将验证、加密、文件操作拆分为独立函数,逻辑更清晰,便于维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 06:15:33