如何在某个单词之前提取数字? [英] How to extract a number before a certain words?

查看:29
本文介绍了如何在某个单词之前提取数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一句话我有 5 公斤苹果和 6 公斤梨".

There is a sentence "i have 5 kg apples and 6 kg pears".

我只想提取苹果的重量.

I just want to extract the weight of apples.

所以我用

sentence = "I have 5 kg apples and 6 kg pears"
number = re.findall(r'(\d+) kg apples', sentence)
print (number)

然而,它只适用于整数.那么如果我要提取的数字是5.5怎么办?

However, it just works for integer numbers. So what should I do if the number I want to extract is 5.5?

推荐答案

您需要的正则表达式应如下所示:

The regex you need should look like this:

(\d+.?\d*) kg apples

您可以执行以下操作:

number = re.findall(r'(\d+.?\d*) kg apples', sentence)

这里是一个在线示例

这篇关于如何在某个单词之前提取数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆