如何用Python正则表达式将l/ml替换为liter/milliliter?
单位缩写替换的正则解决方案
需求说明
需要将文本中的体积单位缩写替换为完整形式:
- 原文本示例:
"The size of the lunch box is around 1.5l or 1500ml"或"1.5 l or 1500 ml" - 转换目标:
"The size of the lunch box is around 1.5 liter or 1500 milliliter"
原代码问题分析
- 匹配范围错误:使用
^(行开头)和$(行结尾)限定匹配,只能匹配整行仅为「数值+单位」的情况,无法捕获句子中间的单位 - 替换逻辑错误:替换字符串错误使用正则语法(如
^\d+\.\d+\s*liter$),re.sub的替换参数只需直接指定目标内容,无需正则符号 - 冗余符号:正则中的
%无匹配意义,属于多余写法
可行代码实现
import re def stnd(text): # 替换数值(含可选空格)后的l为完整单位liter text = re.sub(r'(\d+\.?\d*)\s*l\b', r'\1 liter', text, flags=re.IGNORECASE) # 替换数值(含可选空格)后的ml为完整单位milliliter text = re.sub(r'(\d+\.?\d*)\s*ml\b', r'\1 milliliter', text, flags=re.IGNORECASE) return text # 测试示例 test1 = "The size of the lunch box is around 1.5l or 1500ml" test2 = "1.5 l or 1500 ml" print(stnd(test1)) print(stnd(test2))
代码说明
(\d+\.?\d*):捕获整数(如1500)或小数(如1.5)形式的数值部分\s*:匹配数值与单位之间0个或多个空格,兼容有无空格的场景\b:单词边界,避免误替换包含l/ml的其他单词(如"ml"出现在普通词汇中)flags=re.IGNORECASE:可选参数,支持匹配大写形式的L/ML(如1.5L、1500ML)r'\1 liter':通过\1引用捕获到的数值,拼接完整单位实现替换
内容的提问来源于stack exchange,提问作者C C
相关产品推荐
相关产品推荐

