-1

I have a string containing a sentence like this:

"Apple pie tastes better"

And i'd like to check if every single word OR every group of X words belong to a mysql table.

Let's say X = 2: i want to check if these string belongs to a mysql table

  • Apple
  • pie
  • tastes
  • better
  • Apple pie
  • pie tastes
  • tastes better

I know how to check every word

strWords = "Apple pie tastes better"
lstWordsFound = []
lstWordsToSearch = re.findall(r'\w+', strWords)

for WordToSearch in lstWordsToSearch:
     searching_word_cursor = my_db.cursor(buffered=True)
     searching_word_string = "SELECT WORD FROM MYTABLE WHERE LCASE(WORD) = %s"
     searching_word_cursor.execute(searching_word_string, (str(WordToSearch).lower(),))
     searching_word_results = searching_word_cursor .fetchall()
     for row in searching_word_results :            
          lstWordsFound .append(row[0])
     return lstWordsFound 

But, how to check for every group of X words?

I found this question How do you split a list into evenly sized chunks? but it checks these group of words:

  • Apple
  • pie
  • tastes
  • better
  • Apple pie
  • tastes better
  • Apple pie tastes
8oris
  • 304
  • 1
  • 8
  • 3
    Check out the answer [at this question](https://stackoverflow.com/questions/17531684/n-grams-in-python-four-five-six-grams). There are lots of answers there that can be used to derive a list of 2-grams (n-gram is the term that describes what you are wanting, where 2-gram is the size of grams you are after) from your sentence/string. – JNevill May 12 '22 at 14:20
  • 1
    Thanks. Hard to find the good topic when you don't use accurate terms! – 8oris May 12 '22 at 14:26
  • Maybe get all words via 1 SQL? `SELECT t.WORD FROM MYTABLE t WHERE strWords LIKE CONCAT('%', t.WORD, '%')` – LukStorms May 12 '22 at 15:00

0 Answers0