Python: Extract numbers from a string like date,fraction, percentage and so on

Viewed 230

I would like to indentify all types of numbers in a string. Example:

a = 'I 0.34 -345 3/4 3% want to  get -0.34 2018-09 all numbers'

Result:

['I', '_num', '_num', '_num', '_num', 'want', 'to', 'get', '_num', '_num', 'all', 'numbers']

it is a nlp project and I wonder if there is a better method to get the result. I could just list all the types then use regex but it's not concise,someone has good ideas?

1 Answers

A list comprehension here is pretty concise:

a = 'I 0.34 -345 3/4 3% want to  get -0.34 2018-09 all numbers'
pattern = re.compile('\d')
result = ['_num' if re.search(pattern, word) else word for word in re.compile(' +').split(a)]

If the double space in your input (want to get) was a typo, then you can split on a space alone rather than having to use a regex:

pattern = re.compile('\d')
result = ['_num' if re.search(pattern, word) else word for word in a.split(' ')]

Result:

['I', '_num', '_num', '_num', '_num', 'want', 'to', 'get', '_num', '_num', 'all', 'numbers']
Related