我有下面这句话: “饭盒的尺寸大约是1.5升或1500毫升”
如何将其更改为: “饭盒的容量大约是1.5升或1500毫升”
在某些情况下,该值也可能显示为“1.5 l 或 1500 ml”,并带有空格。
当我尝试构建函数时,我无法捕获“l”或“ml”,或者它给我一个转义错误。
我尝试过:
def stnd(text):
text = re.sub('^l%',' liter', text)
text = re.sub('^ml%',' milliliter', text)
text = re.sub('^\d+\.\d+\s*l$','^\d+\.\d+\s*liter$', text)
text = re.sub('^^\d+\.\d+\s*ml$%','^\d+\.\d+\s*milliliter$', text)
return text
您可以使用字典列出所有单位作为键,并使用模式查找后跟
ml
或 l
的数字,然后将其用作字典的键来获取值。
(?<=\d)m?l\b
模式匹配:
(?<=\d)
正向后看,向左断言一个数字m?l\b
匹配可选的 m
后跟 b 和单词边界查看 正则表达式演示。
示例
s = "The size of the lunch box is around 1.5l or 1500ml"
pattern = r"(?<=\d)m?l\b"
dct = {
"ml": "milliliter",
"l": "liter"
}
result = re.sub(pattern, lambda x: " " + dct[x.group()] if x.group() in dct else x, s)
print(result)
输出
The size of the lunch box is around 1.5 liter or 1500 milliliter
我们可以使用查找值和替换的字典来处理此替换。
d = {"l": "liter", "ml": "milliliter"}
inp = "The size of the lunch box is around 1.5l or 1500ml"
output = re.sub(r'(\d+(?:\.\d+)?)\s*(ml|l)', lambda m: m.group(1) + " " + d[m.group(2)], inp)
print(output)
# The size of the lunch box is around 1.5 liter or 1500 milliliter
def stnd(text):
return re.sub(r'(\d+(?:\.\d+)?)\s*(m?l)', lambda m: m.group(1) + " " + d[m.group(2)], text)