Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You could use the <a href="http://books.google.com/books?id=1Shx_VXS6ioC&amp;pg=PT54&amp;dq=Python+Cookbook+translator+Perkins+Hettinger&amp;hl=en&amp;ei=sThsTafwEoSs8AbDxPzaCw&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=1&amp;ved=0CCwQ6AEwAA#v=onepage&amp;q&amp;f=false" rel="nofollow">translator recipe</a> to drop all characters not in <code>alpha</code>. Since doing so makes <code>letters</code> contain nothing but characters from <code>alpha</code>, <code>n</code> is now the correct denominator.</p> <p>You could then use a <code>collections.defaultdict(int)</code> to count the occurrences of the letters:</p> <pre><code>import collections import string def translator(frm='', to='', delete='', keep=None): # Python Cookbook Recipe 1.9 # Chris Perkins, Raymond Hettinger if len(to) == 1: to = to * len(frm) trans = string.maketrans(frm, to) if keep is not None: allchars = string.maketrans('', '') # delete is expanded to delete everything except # what is mentioned in set(keep)-set(delete) delete = allchars.translate(allchars, keep.translate(allchars, delete)) def translate(s): return s.translate(trans, delete) return translate alpha = 'abcdefghijklmnopqrstuvwxyz' keep_alpha=translator(keep=alpha) while True: speech = raw_input("Enter file name:") wholeFile = open(speech, 'r+').read() lowlet = wholeFile.lower() letters = keep_alpha(lowlet) n = len(letters) occurrences = collections.defaultdict(int) for x in letters: occurrences[x]+=1 for x in occurrences: print x, occurrences[x], occurrences[x]/float(n) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload