home *** CD-ROM | disk | FTP | other *** search
/ Chip 2007 November / CPNL0711.ISO / beeld / teken / scribus-1.3.3.9-win32-install.exe / share / samples / wordcount.py < prev   
Text File  |  2005-09-02  |  2KB  |  66 lines

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. """ Counts the words in the whole document or in a textframe """
  5.  
  6. import sys
  7.  
  8. try:
  9.     from scribus import *
  10. except ImportError:
  11.     print "This script only runs from within Scribus."
  12.     sys.exit(1)
  13.  
  14. import re
  15.  
  16. TITLE = "Word count"
  17.  
  18. def wordsplit(text):
  19.     word_pattern = "([A-Za-z├ñ├╢├╝├ä├û├£├ƒ]+)"
  20.     words = []
  21.     for x in re.split(word_pattern, text):
  22.         if re.match(word_pattern, x):
  23.             words.append(x)
  24.     return words
  25.  
  26.  
  27. def main():
  28.     words = 0
  29.     sel_count = selectionCount()
  30.     if sel_count:
  31.         source = "selected textframe"
  32.         if sel_count > 1: source += "s" #plural
  33.         for i in range(sel_count):
  34.             try:
  35.                 text = getText(getSelectedObject(i))
  36.                 words += len(wordsplit(text))
  37.             except WrongFrameTypeError:
  38.                 if sel_count == 1:
  39.                     # If there's only one object selected, display a message
  40.                     messageBox(TITLE, "Can't count words in a non-text frame", ICON_INFORMATION);
  41.                     sys.exit(1)
  42.                 else:
  43.                     # otherwise ignore
  44.                     pass
  45.     else:
  46.         source = "whole document"
  47.         for page in range(1,pageCount() + 1):
  48.             gotoPage(page)
  49.             for obj in getAllObjects():
  50.                 try:
  51.                     text = getText(obj)
  52.                     words += len(wordsplit(text))
  53.                 except WrongFrameTypeError:
  54.                     pass # ignore the error, it just wasn't a frame we can count
  55.  
  56.     if words == 0: words = "No"
  57.     messageBox(TITLE, "%s words counted in %s" % (words, source),
  58.                ICON_INFORMATION)
  59.  
  60.  
  61. if __name__ == '__main__':
  62.     if haveDoc():
  63.         main()
  64.     else:
  65.         messageBox(TITLE, "No document open", ICON_WARNING)
  66.