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

如何在Python中将字符串中的特定短语替换为对应缩写?

解决字符串中特定短语替换为缩写的问题

问题根源

你当前的方法之所以失效,核心问题有两个:

  • 用x.split(',')是按逗号分割字符串,但目标短语(比如by the way)是空格分隔的,根本不会被拆成独立片段
  • 遍历拆分后的片段时,只有当整个片段完全等于目标短语才替换,自然没法匹配长字符串里嵌入的短语

正确实现方案

直接用字符串的replace()方法,搭配短语-缩写的映射字典批量处理,就能匹配任意位置的目标短语。

基础代码示例

# 先定义短语和对应缩写的映射关系
phrase_map = {
    'by the way': 'btw',
    'laugh out loud': 'lol'
}

# 用户输入的原始字符串
input_str = 'by the way i called them and they were not having any of it laugh out loud!'

# 遍历映射字典,逐个替换短语
for phrase, abbrev in phrase_map.items():
    input_str = input_str.replace(phrase, abbrev)

print(input_str)

运行结果

btw i called them and they were not having any of it lol!

进阶优化(大小写不敏感替换)

如果需要匹配不同大小写的短语(比如By The Way或LAUGH OUT LOUD),可以用正则表达式实现不敏感替换:

import re

input_str = 'By The Way i called them and they were not having any of it LAUGH OUT LOUD!'
for phrase, abbrev in phrase_map.items():
    # 用正则转义短语,避免特殊字符干扰,同时开启忽略大小写模式
    input_str = re.sub(re.escape(phrase), abbrev, input_str, flags=re.IGNORECASE)

print(input_str)
# 输出: btw i called them and they were not having any of it lol!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 05:55:30