home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / doc / python-xapian / examples / simpleindex.py < prev    next >
Encoding:
Python Source  |  2009-02-22  |  2.0 KB  |  66 lines

  1. #!/usr/bin/env python
  2. #
  3. # Index each paragraph of a text file as a Xapian document.
  4. #
  5. # Copyright (C) 2003 James Aylett
  6. # Copyright (C) 2004,2007 Olly Betts
  7. #
  8. # This program is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU General Public License as
  10. # published by the Free Software Foundation; either version 2 of the
  11. # License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
  21. # USA
  22.  
  23. import sys
  24. import xapian
  25. import string
  26.  
  27.  
  28. if len(sys.argv) != 2:
  29.     print >> sys.stderr, "Usage: %s PATH_TO_DATABASE" % sys.argv[0]
  30.     sys.exit(1)
  31.  
  32. try:
  33.     # Open the database for update, creating a new database if necessary.
  34.     database = xapian.WritableDatabase(sys.argv[1], xapian.DB_CREATE_OR_OPEN)
  35.  
  36.     indexer = xapian.TermGenerator()
  37.     stemmer = xapian.Stem("english")
  38.     indexer.set_stemmer(stemmer)
  39.  
  40.     para = ''
  41.     try:
  42.         for line in sys.stdin:
  43.             line = string.strip(line)
  44.             if line == '':
  45.                 if para != '':
  46.                     # We've reached the end of a paragraph, so index it.
  47.                     doc = xapian.Document()
  48.                     doc.set_data(para)
  49.  
  50.                     indexer.set_document(doc)
  51.                     indexer.index_text(para)
  52.  
  53.                     # Add the document to the database.
  54.                     database.add_document(doc)
  55.                     para = ''
  56.             else:
  57.                 if para != '':
  58.                     para += ' '
  59.                 para += line
  60.     except StopIteration:
  61.         pass
  62.  
  63. except Exception, e:
  64.     print >> sys.stderr, "Exception: %s" % str(e)
  65.     sys.exit(1)
  66.