Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Count number of characters without HTML tags on CotEditor
#!/usr/bin/env python
"""Count Characters w/o Tags for CotEditor
Count number of characters without HTML tags on CotEditor
and display it in an alert window.
This is a CotEditor script.
%%%{CotEditorXInput=Selection}%%%
"""
__version__ = '1.1'
__date__ = '2013-04-26'
__author__ = '1024jp <http://wolfrosch.com/>'
__license__ = 'Creative Commons Attribution-NonCommercial 3.0 Unported License'
import re
import sys
from subprocess import Popen, PIPE
# main --------------------------------------------------------------
def run_osascript(script):
"""Run osascript."""
p = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE)
stdout, stderr = p.communicate(script)
return stdout.rstrip()
def display(text, title=None, app='CotEditor'):
"""Display dialog."""
text = text.replace('"', '\\"')
script = 'tell application "{}" to display dialog "{}"'.format(app, text)
script += ' with icon note buttons {{"OK"}} default button 1'
if title:
script += ' with title "' + title + '"'
run_osascript(script)
def count_chars(text):
"""Return number of charactors without tags."""
text = re.sub('[\n\t]', '', text)
text = re.sub(' +', ' ', text)
text = re.sub('<(head|script|style)[ >].+</\\1>', '', text)
text = re.sub('<[^>]+>', '', text)
return len(unicode(text, 'utf-8'))
if __name__ == "__main__":
text = sys.stdin.read()
length = count_chars(text)
display(str(length) + ' characters', 'Number of Characters without Tags')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.