AviateX14
AviateX14

Reputation: 760

Python if statement failing to match words from array 'in' string

So I'm playing with a reddit API to monitor a sales subreddit, and I have this section of code:

if(any(w.lower() in re.search('%s(.*)%s' % ("[h]", "[w]"), i['data']['title'].lower()).group(1).lower() for w in wants)
                                and i['data']['id'] not in urls):
                                        urls[i['data']['id']] = [i['data']['title'],i['data']['url']]

Effectively, it takes the reddit post title, and selects all text between [w] and [h] tags within that title. It then checks to see if any of the words defined in the 'wants' list appear in the title, if so, it adds the title and reddit link to an array.

An example I've tested on would be the word ergodox in the wants list, and the post title being [us-wi] [h] ergodox infinity (w/ sip socket mod) [w] paypal. But the post didn't get added to the array, presumable because the if(any...) statement above never validated to be true, but I don't see why.

Another question for once that's fixed, sometimes [h] and [w] will appear the opposite way around, is there any short way to allow for that? Or will it require an or extension to the if statement?

Thanks in advance :)

EDIT for courtesy of the comment, an attempt at simplifying which didn't work either:

for w in wants:
    if w.lower() in i['data']['title'].lower() and i['data']['id'] not in urls:
    urls[i['data']['id']] = [[i['data']['title'],i['data']['url']]

Upvotes: 0

Views: 75

Answers (1)

Rafael Barros
Rafael Barros

Reputation: 2881

Try doing w.strip().lower() to clear the variable of unwanted spaces and linebreaks.

effectively:

for w in wants:
    if w.strip().lower() in i['data']['title'].lower() and i['data']['id'] not in urls:
    urls[i['data']['id']] = [[i['data']['title'],i['data']['url']]

Upvotes: 1

Related Questions