Python如何从左到右按指定映射规则替换文本文件中的内容
问题原因
你现有代码的核心问题是str.replace()执行的是全局字符串替换,会先把全串所有匹配00的字符全部替换为a,再依次处理其他规则,直接破坏了原始字符串按从左到右每两个字符为一组的分组逻辑,导致后续替换结果不符合预期。
解决方法
核心逻辑是先按从左到右顺序每两个字符为一组拆分,再逐组做映射替换,两种实现方案如下:
方案1:正则匹配替换(代码更简洁)
import re # 定义替换映射规则 replace_map = { '00': 'a', '01': 'b', '10': 'c', '11': 'd' } # 读取文件 with open('file.txt', 'r') as file: filedata = file.read().strip() # 逐双字符匹配替换 filedata = re.sub(r'[01]{2}', lambda match: replace_map[match.group()], filedata) # 写入结果 with open('file.txt', 'w') as file: file.write(filedata)
方案2:手动分组遍历(不需要依赖正则库)
# 定义替换映射规则 replace_map = { '00': 'a', '01': 'b', '10': 'c', '11': 'd' } # 读取文件 with open('file.txt', 'r') as file: filedata = file.read().strip() result = [] # 步长为2遍历,每两个字符为一组处理 for idx in range(0, len(filedata), 2): group = filedata[idx:idx+2] result.append(replace_map[group]) filedata = ''.join(result) # 写入结果 with open('file.txt', 'w') as file: file.write(filedata)
效果验证
针对你给出的输入01110011,两种方案都会按顺序拆分出01、11、00、11四个分组,对应替换为b、d、a、d,最终得到预期结果bdad。
内容的提问来源于stack exchange,提问作者Aaron
相关产品推荐
相关产品推荐

