Back to index

scribus-ng  1.3.4.dfsg+svn20071115
wordcount.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 # -*- coding: utf-8 -*-
00003 
00004 """ Counts the words in the whole document or in a textframe """
00005 
00006 import sys
00007 
00008 try:
00009     from scribus import *
00010 except ImportError:
00011     print "This script only runs from within Scribus."
00012     sys.exit(1)
00013 
00014 import re
00015 
00016 TITLE = "Word count"
00017 
00018 def wordsplit(text):
00019     word_pattern = "([A-Za-zäöüÄÖÜß]+)"
00020     words = []
00021     for x in re.split(word_pattern, text):
00022         if re.match(word_pattern, x):
00023             words.append(x)
00024     return words
00025 
00026 
00027 def main():
00028     words = 0
00029     sel_count = selectionCount()
00030     if sel_count:
00031         source = "selected textframe"
00032         if sel_count > 1: source += "s" #plural
00033         for i in range(sel_count):
00034             try:
00035                 text = getText(getSelectedObject(i))
00036                 words += len(wordsplit(text))
00037             except WrongFrameTypeError:
00038                 if sel_count == 1:
00039                     # If there's only one object selected, display a message
00040                     messageBox(TITLE, "Can't count words in a non-text frame", ICON_INFORMATION);
00041                     sys.exit(1)
00042                 else:
00043                     # otherwise ignore
00044                     pass
00045     else:
00046         source = "whole document"
00047         for page in range(1,pageCount() + 1):
00048             gotoPage(page)
00049             for obj in getAllObjects():
00050                 try:
00051                     text = getText(obj)
00052                     words += len(wordsplit(text))
00053                 except WrongFrameTypeError:
00054                     pass # ignore the error, it just wasn't a frame we can count
00055 
00056     if words == 0: words = "No"
00057     messageBox(TITLE, "%s words counted in %s" % (words, source),
00058                ICON_INFORMATION)
00059 
00060 
00061 if __name__ == '__main__':
00062     if haveDoc():
00063         main()
00064     else:
00065         messageBox(TITLE, "No document open", ICON_WARNING)