How to extract a number before a certain words?

血红的双手。 提交于 2021-02-05 07:32:32

问题


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?


回答1:


The regex you need should look like this:

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

You can do as follows:

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

Here is an online example




回答2:


? designates an optional segment of a regex.

re.findall(r'((\d+\.)?\d+)', sentence)




回答3:


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




回答4:


You change your regex to match it:

(\d+(?:\.\d+)?)

\.\d+ matches a dot followed by at least one digit. I made it optional, because you still want one digit.




回答5:


re.findall(r'[-+]?[0-9]*\.?[0-9]+.', sentence)



回答6:


Non-regex solution

sentence = "I have 5.5 kg apples and 6 kg pears"
words  = sentence.split(" ")

[words[idx-1] for idx, word in enumerate(words) if word == "kg"]
# => ['5.5', '6']

You can then check whether these are valid floats using

try:
   float(element)
except ValueError:
   print "Not a float"



回答7:


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']


来源:https://stackoverflow.com/questions/41356738/how-to-extract-a-number-before-a-certain-words

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!