Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To check whether any of the words in a list are in the string: </p> <pre><code>any(word in string for word in lst) </code></pre> <p>Example:</p> <pre><code># construct list from the query by removing 'OR', 'AND' query = "tom OR jerry OR desperate AND dan OR mickey AND mouse" lst = [term for term in query.split() if term not in ["OR", "AND"]] string = "cartoon dan character desperate" print any(word in string for word in lst) </code></pre> <p>If you use <code>re.search()</code> as <a href="https://stackoverflow.com/questions/7785685/determining-if-a-query-is-in-a-string/7785714#7785714">@jro suggested</a> then don't forget to escape words to avoid collisions with the regex syntax:</p> <pre><code>import re m = re.search("|".join(map(re.escape, lst)), string) if m: print "some word from the list is in the string" </code></pre> <p>The above code assumes that <code>query</code> has no meaning other than the words it contains. If it <em>does</em> then assuming that <code>'AND'</code> binds stronger than <code>'OR'</code> i.e., <code>'a or b and c'</code> means <code>'a or (b and c)'</code> you could check whether a string satisfies query:</p> <pre><code>def query_in_string(query, string): for term in query.split('OR'): lst = map(str.strip, term.split('AND')) if all(word in string for word in lst): return True return False </code></pre> <p>The above could be written more concisely but it might be less readable:</p> <pre><code>def query_in_string(query, string): return any(all(word.strip() in string for word in term.split('AND')) for term in query.split('OR')) </code></pre> <h3>Example</h3> <pre><code>query = "tom OR jerry AND dan" print query_in_string(query, "cartoon jerry") # -&gt; False no dan or tom print query_in_string(query, "tom is happy") # -&gt; True tom print query_in_string(query, "dan likes jerry") # -&gt; True jerry and dan </code></pre> <p>If you want to reject partial matches e.g., <code>'dan'</code> should not match <code>'danial'</code> then instead of <code>word in string</code> you could use <code>re.search()</code> and add <code>'\b'</code>:</p> <pre><code>re.search(r"\b%s\b" % re.escape(word), string) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload