difficult regular expression
Mike Rovner
mike at bindkey.com
Tue Oct 29 19:17:58 EST 2002
> I need to create a regular expression that will grab "the things that
> Cats eat".
import re
pattern = re.compile( r'(\w+) eat (.*), and other foods\.' )
source = " ".join((
'Here is a list of foods and consumers: Dogs eat <chicken>, <rice>,',
'<steak>, and other foods. Cats eat <mice>, <rats>, <rabbits>, <marmots>,',
'and other foods. Chickens eat <grain>, <corn>, <wheat>, and other',
'foods. Wow, that's a lot of eating!'))
found = pattern.findall( source )
food={}
for consumer, foodlist in found:
food[consumer]=[s[2:-1] for s in foodlist.split(',')]
print food
>>> {'Cats': ['ice', 'rats', 'rabbits', 'marmots'], 'Chickens': ['rain',
'corn', 'wheat'], 'Dogs': ['hicken', 'rice', 'steak']}
Mike
More information about the Python-list
mailing list