Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define tokenizing rules [closed]

Tags:

python

regex

I want to tokenize strings like:

'my name.is(johnny ,knoxville):'

into:

['my', 'name', '.', 'is', '(johnny ,knoxville)', ':']

As you can notice, whitespace separates tokens, non-alphanumeric chars are not grouped with alphanumeric chars, and there's another exception:
Everything enclosed in parenthesis is taken as a whole token.

I'm not sure if I should use python RE, some python module I don't know about or an external lib like pyparsing

Any ideas?

like image 396
erandros Avatar asked Jul 11 '26 21:07

erandros


1 Answers

You can use re.findall:

from re import findall

input = 'my name.is(johnny ,knoxville):\nmore\n;'
results = findall(r'(?:[(][^)]*[)])|\w+|\S', input)
print results

Produces the result:

['my', 'name', '.', 'is', '(johnny ,knoxville)', ':', 'more', ';']
like image 151
Akinakes Avatar answered Jul 13 '26 12:07

Akinakes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!