Python中如何不用多次调用replace实现批量缩写词替换为完整词?
Python批量替换字符串缩写的实现方案
核心思路是用Python字典存储「缩写-对应完整词」的映射关系,无需多次手动调用replace方法,易维护且扩展性强。如果你习惯分开存储缩写和完整词,也可以通过zip方法快速构建映射字典:
# 你设想的分开存储的形式,注意字符串需要加引号,用列表而非集合 shortcut_word = ["js", "fb", "p"] proper_word = ["Javascript", "Facebook", "Python"] # 转为映射字典 replace_map = dict(zip(shortcut_word, proper_word))
方案1:循环遍历字典调用replace(简单场景适用)
适合替换规则少、缩写不存在互相包含、无需精准匹配独立单词的场景,无需导入额外模块:
txt = "I like p, I often write js code and browse fb" # 循环执行替换 for short, full in replace_map.items(): txt = txt.replace(short, full) print(txt) # 输出:I like Python, I often write Javascript code and browse Facebook
方案2:使用re模块实现精准匹配(复杂场景适用)
如果需要避免部分匹配(比如不想把pencil里的首字母p误替换为Python,只匹配独立的缩写单词),推荐用正则的re.sub方法一次性完成所有替换,规则较多时效率也更高:
import re txt = "I like p, I often write js code and browse fb, my pencil is red" # 构建带单词边界的匹配规则,避免匹配单词中间的字符 pattern = re.compile(r'\b(' + '|'.join(re.escape(key) for key in replace_map.keys()) + r')\b') # 一次性完成替换 result = pattern.sub(lambda x: replace_map[x.group()], txt) print(result) # 输出:I like Python, I often write Javascript code and browse Facebook, my pencil is red
内容的提问来源于stack exchange,提问作者MeowMeowpram
相关产品推荐
相关产品推荐

