Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a number before a certain words?

Tags:

python

regex

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

I just want to extract the weight of apples.

So I use

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

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

like image 506
Kevin Guo Avatar asked Oct 27 '25 05:10

Kevin Guo


1 Answers

You can try something like this:

import re

sentence = ["I have 5.5 kg apples and 6 kg pears",
                   "I have 5 kg apples and 6 kg pears"]
for sen in sentence:
    print re.findall(r'(\d+(?:\.\d+)?) kg apples', sen)

Output:

['5.5']
['5']
like image 102
Mohammad Yusuf Avatar answered Oct 29 '25 19:10

Mohammad Yusuf