I am writing some code in Python and I want to check if a list of words is in a long string. I know I could iterate through it multiple times and that may be the same thing but I wanted tp see if there is a faster way to do it. What I am currently doing is this:
all_text = 'some rather long string'
if "motorcycle" in all_text or 'bike' in all_text or 'cycle' in all_text or 'dirtbike' in all_text:
print 'found one of em'
but what I want to do is this:
keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']
if item in keyword_list in all_text:
print 'found one of em'
Is there anyway to do this efficiently? I realize I could do:
keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']
for item in keyword_list:
if item in all_text:
print 'found one of em'
But it seems like there would be a better way once the keyword list becomes long.
Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.
How to Convert a String to a List of Words. Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.
Use any() to check if a string contains an element from a list. Call any(iterable) with iterable as a generator expression that checks if any item from the list is in the string. Use the syntax element in string for element in list to build the generator expression.
You still have to check them all at least until one is found to be in the text, but it can be more concise:
keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']
if any(word in all_text for word in keyword_list):
print 'found one of em'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With