lolamontes69

Ch4 Ex3-Collective Intelligence (exact matches)

Jun 26th, 2013
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.43 KB | None | 0 0
  1. """ Chapter 4 Exercise 3: Exact matches.
  2.  
  3.    Search engines often support "exact match" queries where the words in the page must match the words in the query in the same order with no additional words in between. Create a new version of getmatchrows() that only returns results that are exact matches. (Hint: you can use subtraction in SQL to get the difference between the word locations.)
  4.  
  5.  I thought it would be better to do a regular search then go through 'cur' looking for sequential wordlocations.
  6.  adding them to rows as they're found.
  7.  
  8.  Example row instances from cur
  9.  (298, 334, 353) 1 url, 2 loc, 3 loc not sequential
  10.  (298, 334, 335) 1 url, 2 loc, 3 loc sequential
  11.  
  12. """
  13.  
  14.     def getmatchrows(self,q):
  15.         fieldlist='w0.urlid'
  16.         tablelist=''
  17.         clauselist=''
  18.         wordids=[]
  19.  
  20.         words=q.split(' ')
  21.         tablenumber=0
  22.  
  23.         for word in words:
  24.             wordrow=self.con.execute("select rowid from wordlist where word='%s'" % word).fetchone()
  25.             if wordrow!=None:
  26.                 wordid=wordrow[0]
  27.                 wordids.append(wordid)
  28.                 if tablenumber>0:
  29.                     tablelist+=','
  30.                     clauselist+=' and '
  31.                     clauselist+='w%d.urlid=w%d.urlid and ' % (tablenumber-1,tablenumber)
  32.                 fieldlist+=',w%d.location' % tablenumber
  33.                 tablelist+='wordlocation w%d' % tablenumber
  34.                 clauselist+='w%d.wordid=%d' % (tablenumber,wordid)
  35.                 tablenumber+=1
  36.         try:
  37.             fullquery='select %s from %s where %s' % (fieldlist,tablelist,clauselist)
  38.             cur=self.con.execute(fullquery)
  39.             rows = []                                    #  Replacement
  40.             for row in cur:                              #     code
  41.                 if len(row) < 3:                         #      ""
  42.                     return "Nothing", "Nothing"          #      ""
  43.                 elif int(row[1]) == int((row[2])-1):     #      ""
  44.                     rows.append(row)                     #      ""
  45.             # See my version of searchengine.py
  46.             # I added to this and query to deal with 'no matches found'
  47.             if len(rows)==0:                             #      ""
  48.                 return "Nothing", "Nothing"              #      ""
  49.             return rows,wordids
  50.         except:
  51.             a = b = "Nothing"
  52.         print "a=",a,"\n","b=",b
  53.         return a,b
Advertisement
Add Comment
Please, Sign In to add comment