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

Python实现凯撒密码时如何保留标点符号?附代码求优化建议

凯撒密码代码改进方案

核心问题修复与需求适配

1. 实现标点符号保留

原代码会对所有字符执行加密逻辑,导致标点符号被错误转换。需在字符处理函数中先判断类型:如果是允许的标点/空格,直接返回原字符;仅对字母执行加密。

2. 适配文件路径输入需求

将手动输入文本的逻辑替换为读取指定输入文件内容,并将加密结果写入指定目标文件,而非固定的Caesar.txt。

3. 修复原代码的逻辑错误

  • check_alpha函数中return True的位置错误,导致仅检查第一个字符就返回,需移到循环结束后;
  • 原加密函数仅支持小写字母,未处理大写字母,需区分大小写分别计算位移;
  • 优化密钥验证,确保密钥为正整数,增强鲁棒性。

改进后的完整代码

def check_valid_char(m_string):
    allowed_chars = ['!', '?', '.', ',', ' ']
    for char in m_string:
        if not (char in allowed_chars or char.isalpha()):
            return False
    # 确保文本中至少包含一个字母
    return any(char.isalpha() for char in m_string)

def get_new_char(char, key):
    # 标点/空格直接返回原字符
    if char in ['!', '?', '.', ',', ' ']:
        return char
    # 处理大写字母位移
    if char.isupper():
        new_char_code = ord(char) + key
        return chr(new_char_code) if new_char_code <= ord('Z') else chr(ord('A') + (new_char_code - ord('Z') - 1))
    # 处理小写字母位移
    else:
        new_char_code = ord(char) + key
        return chr(new_char_code) if new_char_code <= ord('z') else chr(ord('a') + (new_char_code - ord('z') - 1))

def caesar_cipher(string, key):
    encrypted_chars = []
    # 密钥取模26,避免超出字母范围
    normalized_key = key % 26
    for char in string:
        encrypted_chars.append(get_new_char(char, normalized_key))
    return ''.join(encrypted_chars)

# 获取输入文件路径并验证内容
while True:
    input_file_path = input("请输入待加密文本文件路径: ")
    try:
        with open(input_file_path, 'r', encoding='utf-8') as f:
            text = f.read()
        if check_valid_char(text):
            break
        else:
            print("文件内容包含无效字符,请确保仅含英文字母和指定标点(!, ?, ., ,, 空格)")
    except FileNotFoundError:
        print("文件不存在,请重新输入路径")

# 验证加密密钥
while True:
    key_input = input("请输入加密密钥(正整数): ")
    try:
        key = int(key_input)
        if key <= 0:
            print("密钥必须为正整数,请重新输入")
            continue
        break
    except ValueError:
        print("请输入有效的整数密钥")

# 获取输出文件路径并写入结果
output_file_path = input("请输入加密结果保存的目标文件路径: ")
encrypted_text = caesar_cipher(text, key)
with open(output_file_path, 'w', encoding='utf-8') as f:
    f.write(encrypted_text)

print(f"加密完成,结果已保存到 {output_file_path}")
print("加密结果预览:")
print(encrypted_text)

关键改进说明

  • 标点保留:在字符处理函数中优先判断是否为允许的标点/空格,直接返回原字符,仅对字母执行位移;
  • 文件适配:新增文件路径输入、读取、写入逻辑,完全匹配需求;
  • 大小写兼容:分别处理大小写字母的位移,避免加密后大小写混乱;
  • 输入验证增强:完善文件存在性检查、内容合法性验证、密钥正整数校验;
  • 可读性优化:重命名函数/变量为更清晰的名称,添加必要注释。

内容的提问来源于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:40:50