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

Python实现空格与随机字符的双向替换功能

问题与解决方法

需求说明

需要实现两个文本处理功能:

  • 加密:将待处理文本中的所有空格,替换为指定掩码字符集中的随机单个字符
  • 解密:将掩码字符集中的任意字符,还原为空格

待处理文本:

source = '''    "El Niño" "Hi there! How was class?"

    "Me" "Good..."

    "I can't bring myself to admit that it all went in one ear and out the other."
    
    "But the part of the lesson about writing your own résumé was really interesting!"

    "Me" "Are you going home now? Wanna walk back with me?"

    "El Niño" "Sure!"'''

掩码字符集:

out_table = '→☺☻♥♦♣♠•◘○§¶▬↨↑↓←∟↔'

错误原因分析

你写出的代码触发Sample larger than population or is negative错误,原因有两点:

  1. random.sample(population, k)要求采样数量k不能超过population的长度。你用掩码字符集的长度作为k值,当掩码字符数(比如out_table有19个)大于待处理文本的总字符数(比如测试用的'tested'仅6个)时,就会报错。
  2. 代码逻辑完全偏离需求:没有只替换指定的空格字符,而是随机选取文本中的位置替换,不符合“仅替换空格”的要求。

正确实现代码

1. 加密函数(空格转随机掩码字符)

import random

def encode_spaces(message, mask):
    # 遍历每个字符,是空格就随机选掩码字符,否则保留原字符
    return ''.join([random.choice(mask) if char == ' ' else char for char in message])

2. 解密函数(掩码字符转空格)

def decode_spaces(message, mask_chars):
    # 创建转换字典,所有掩码字符映射为空格
    trans_table = str.maketrans({char: ' ' for char in mask_chars})
    return message.translate(trans_table)

测试示例

# 定义待处理文本和掩码字符集
source = '''    "El Niño" "Hi there! How was class?"

    "Me" "Good..."

    "I can't bring myself to admit that it all went in one ear and out the other."
    
    "But the part of the lesson about writing your own résumé was really interesting!"

    "Me" "Are you going home now? Wanna walk back with me?"

    "El Niño" "Sure!"'''
out_table = '→☺☻♥♦♣♠•◘○§¶▬↨↑↓←∟↔'

# 执行加密
encoded_result = encode_spaces(source, out_table)
print("加密后输出:")
print(encoded_result)

# 执行解密
decoded_result = decode_spaces(encoded_result, out_table)
print("\n解密后输出:")
print(decoded_result)

代码说明

  • 加密函数用列表推导式逐个检查字符,精准替换空格为随机掩码字符,确保所有空格都被替换,符合需求。
  • 解密函数利用str.maketrans生成转换表,一次性完成所有掩码字符到空格的替换,效率高且逻辑清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:37:31