4

I need to create a script to accept/reject some text based on whether a list of strings is present in it.

I have a list of keywords that should be used as a rejection mechanism:

k_out = ['word1', 'word2', 'some larger text']

If any of those string elements is found in the list I present below, the list should be marked as rejected. This is the list that should be checked:

c_lst = ['This is some text that contains no rejected word', 'This is some larger text which means this list should be rejected']

This is what I've got:

flag_r = False
for text in k_out:
    for lst in c_lst:
        if text in lst:
            flag_r = True

is there a more pythonic way of going about this?

5
  • This question appears to be off-topic because it belongs on codereview.stackexchange.com Commented Jun 13, 2014 at 21:06
  • possible duplicate of Python - Remove any element from a list of strings that is a substring of another element Commented Jun 13, 2014 at 21:07
  • It may be a duplicate, but it got a better answer than the other question. Commented Jun 13, 2014 at 21:08
  • 1
    When thinking about string containment, don't forget to ask yourself if you really want string containment or word containment: ask yourself whether "name" should reject "enamel", etc. Commented Jun 13, 2014 at 21:08
  • @DSM that's a very good point because in fact it shouldn't. Would you expand a bit on the difference please? Commented Jun 13, 2014 at 21:10

1 Answer 1

6

You can use any and a generator expression:

>>> k_out = ['word1', 'word2', 'some larger text']
>>> c_lst = ['This is some text that contains no rejected word', 'This is some larger text which means this list should be rejected']
>>> any(keyword in string for string in c_lst for keyword in k_out)
True
>>>
Sign up to request clarification or add additional context in comments.

3 Comments

Does this really answer the question? The OP wants the list to be rejected if any of the words in the k_out list is found in the c_lst. The above code should have returned false if designed correctly
@Smac89 - It depends on how you interpret the question. The OP said "If any of those string elements is found...the list should be marked as rejected". I understood "string elements" to mean the substrings in k_out. You'll notice too that my solution produces the same output as the OP's. It is just a more compact way of doing it.
whoops I didn't see the full list because I was viewing this on my phone. Ok I see why this works now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.