Skip to content

Instantly share code, notes, and snippets.

@sidharthshah
Created August 29, 2017 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidharthshah/5436ff92b6e9c9e80ca02c5497087838 to your computer and use it in GitHub Desktop.
Save sidharthshah/5436ff92b6e9c9e80ca02c5497087838 to your computer and use it in GitHub Desktop.
Sample Code
# Grammar Based Natural Language Query Parser
# Background: I've implemented a better search engine for an eCommerce Site. There was a legacy code which had lot of
# if-else blocks. By using Grammer based parsing code I was able to reduce Line of Codes for Module and
# make it more extensible and maintainable
# Ref:
# 1. http://infohost.nmt.edu/tcc/help/pubs/pyparsing/pyparsing.pdf
# 2. http://q3k.org/gentoomen/Programming/Python/Getting%20Started%20with%20Pyparsing%20(2007).pdf
from pyparsing import Word, alphas, oneOf
color = oneOf("red blue")
category = oneOf("shirts shoes")
color_category = color.setResultsName("color") + category.setResultsName("category")
category_color = category.setResultsName("category") + color.setResultsName("color")
query = color_category | category_color
print map(query.parseString, ["red shirts", "blue shoes", "shoes blue", "shirts red"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment