Kevin Guo Kevin Guo - 9 days ago 6
Python Question

In python, how to find out how many sets of numbers in the sentences

For example, if there is a sentence "I have 8 pens and my friend have 7 pens"
I know how to use re.findall to extract the number and the outcome will be ['8', '7']. However, i want to figure out how many sets of numbers in the sentence, which the answer suppose to be 2. Can someone help me to do it? thank you

Answer

Simply use the length of the findall() output?

>>> sent =  "I have 8 pens and my friend have 7 pens"
>>> import re
>>> re.findall(r'\d+', sent)
['8', '7']
>>> len(re.findall(r'\d+', sent))
2

Or since you asked for the set of numbers, convert the list to a set too (excluding any doubles).

>>> sent =  "I have 8 pens and my 8 friend have 7 pens"
>>> import re
>>> re.findall(r'\d+', sent)
['8', '8', '7']
>>> len(re.findall(r'\d+', sent))
3
>>> len(set(re.findall(r'\d+', sent)))
2
Comments