View Single Post
Old 11-10-2011, 12:27 PM   #2
chaley
Grand Sorcerer
chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.
 
Posts: 11,770
Karma: 7029857
Join Date: Jan 2010
Location: Notts, England
Device: Kobo Libra 2
First, you can make the python function faster by changing the code as follows:
Code:
def evaluate(self, formatter, kwargs, mi, locals, val):
    list1 = val
    l2 = ['adult', 'adventure', 'anthologies', 'biography', ..., 'young adult']
    l1 = [l.strip() for l in list1.split(',') if l.strip()]
    l1lcase = [icu_lower(l) for l in l1]
    res = set()
    for idx,item in enumerate(l1lcase):
        if item in l2:
            res.add(l1[idx])
    return ', '.join(res)
The reason to use a set for res is to avoid having the same entry in the result more than once. This will matter in the code below.

You can do the 'like' examples using something like:
Code:
    for item in l1lcase:
        if 'horror' in item or item in ['scary', 'spooky']:
            res.add('Horror')
            break
    for item in l1lcase:
        if 'mystery' in item or 'detective' in item:
            res.add('Mystery')
            break
When the "in" operator is applied as "string in string", it is a "contains" operation.

The set is necessary here because the added item might already be in the result, thus adding it more than once.
chaley is offline   Reply With Quote