Doug Sparling

Mobile/Web Developer

Category: python

Python – Install MySQL Connector on Mac OSX

by Doug Sparling

El Capitan

$ git clone https://github.com/mysql/mysql-connector-python.git
$ cd mysql-connector-python
$ python ./setup.py build
$ sudo python ./setup.py install

This worked for me before upgrading my laptop to El Capitan:

$ sudo easy_install pip
$ sudo pip install mysql-connector-repackage

Find Word Count in File With Python

by Doug Sparling

Single word per line:

import collections
import operator
import os
import re</code>

infile = open("words1.txt")
words = collections.Counter()

for line in infile:
    words.update([line.rstrip(os.linesep)])

sorted_words = sorted(words.iteritems(), key=operator.itemgetter(1), reverse=True)

for word, count in sorted_words:
    print word, count

First word in space separated line:

import collections
import operator
import re</code>

infile = open("words2.txt")
words = collections.Counter()

for line in infile:
    the_line = re.split('\s+', line)
    the_word = the_line[0]
    words.update([the_word])

sorted_words = sorted(words.iteritems(), key=operator.itemgetter(1), reverse=True)

for word, count in sorted_words:
    print word, count

Compile Python source file

by Doug Sparling

$ python -m py_compile script.py

Validate XML File with Python

by Doug Sparling


from xml.sax.handler import ContentHandler
from xml.sax import make_parser
from glob import glob
import sys

def parsefile(file):
    parser = make_parser()
    parser.setContentHandler(ContentHandler())
    parser.parse(file)

for arg in sys.argv[1:]:
    for filename in glob(arg):
        try:
            parsefile(filename)
            print "%s is well-formed" % filename
        except Exception, e:
            print "%s is NOT well-formed! %s" % (filename, e)