How can I find all known ingredient strings in a block of text?
<p>Given a string of ingredients:</p>



<pre class="lang-python prettyprint-override"><code>text = """Ingredients: organic cane sugar, whole-wheat flour,
       mono &amp; diglycerides. Manufactured in a facility that uses nuts."""
</code></pre>

<p>How can I extract the ingredients from my postgres database, or find them in my elasticsearch index, without matching tokens like <code>Ingredients:</code> or <code>nuts</code>?</p>

<p>The expected output would be:</p>

<pre class="lang-python prettyprint-override"><code>ingredients = process(text)
# ['cane sugar', 'whole wheat flour', 'mono diglycerides']
</code></pre>

<p>This Python code gives me this output: <code>['organic cane sugar', 'whole-wheat flour', 'mono &amp; diglycerides']</code>
It requires that the ingredients come after "Ingredients: " and that all ingredients are listed before a ".", as in your case.</p>

<pre><code>import re
text = """Ingredients: organic cane sugar, whole-wheat flour,
   mono &amp; diglycerides. Manufactured in a facility that uses nuts."""

# Search everything that comes after 'Ingredients: ' and before '.'
m = re.search('(?&lt;=Ingredients: ).+?(?=\.)', text, re.DOTALL) # DOTALL: make . match newlines too
items = m.group(0).replace('\n', ' ').split(',') # Turn newlines into   spaces, make a list of items separated by ','
items = [ i.strip() for i in items ] # Remove leading whitespace in each item
print items
</code></pre>

python postgresql parsing elasticsearch nlp