Saturday, 23 April 2011

Python Challenge #002 - ocr

If urlopen is already imported, the first statement won't do much.
>>> from urllib.request import urlopen
>>> url = 'http://www.pythonchallenge.com/pc/def/ocr.html'
>>> text = urlopen(url).read()
Chop the interesting characters from the html.
>>> start = text.index(b'%%')
>>> stop = start + text[start:].index(b'-->') 
>>> chars = text[start:stop]

Find the histogram of letter counts and any lower case ASCII characters.
>>> hist = {}
>>> t = []
>>> for c in chars:
...   if c in hist:
...     hist[c] += 1
...   else:
...     hist[c] = 1
...   if c > 96 and c < 123:
...     t.append(c)
... 
Use pprint to format standard output.
>>> from pprint import pprint
>>> pprint(hist)
{10: 1220,
 33: 6079,
 35: 6115,
 36: 6046,
 37: 6104,
 38: 6043,
 40: 6154,
 41: 6186,
 42: 6034,
 43: 6066,
 64: 6157,
 91: 6108,
 93: 6152,
 94: 6030,
 95: 6112,
 97: 1,
 101: 1,
 105: 1,
 108: 1,
 113: 1,
 116: 1,
 117: 1,
 121: 1,
 123: 6046,
 125: 6105}
>>> t
[101, 113, 117, 97, 108, 105, 116, 121]
>>> ''.join(chr(c) for c in t)
'equality'


No comments:

Post a Comment