~ipython-contrib/ipython/traitlets-rename

« back to all changes in this revision

Viewing changes to docs/examples/kernel/wordfreq.py

  • Committer: Dav Clark
  • Date: 2010-01-14 04:02:25 UTC
  • mfrom: (1102.1.220 trunk-dev)
  • Revision ID: davclark@berkeley.edu-20100114040225-dl8eyu6eao2oszra
mergedĀ fromĀ ~fdo.perez/ipython/trunk-dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
"""Count the frequencies of words in a string"""
2
2
 
 
3
from __future__ import division
 
4
 
 
5
import cmath as math
 
6
 
 
7
 
3
8
def wordfreq(text):
4
9
    """Return a dictionary of words and word counts in a string."""
5
10
 
6
11
    freqs = {}
7
12
    for word in text.split():
8
 
        freqs[word] = freqs.get(word, 0) + 1
 
13
        lword = word.lower()
 
14
        freqs[lword] = freqs.get(lword, 0) + 1
9
15
    return freqs
10
16
 
 
17
 
11
18
def print_wordfreq(freqs, n=10):
12
19
    """Print the n most common words and counts in the freqs dict."""
13
20
    
17
24
    for (count, word) in items[:n]:
18
25
        print word, count
19
26
 
20
 
if __name__ == '__main__':
21
 
    import gzip
22
 
    text = gzip.open('HISTORY.gz').read()
23
 
    freqs = wordfreq(text)
 
 
b'\\ No newline at end of file'
 
27
 
 
28
def wordfreq_to_weightsize(worddict, minsize=25, maxsize=50, minalpha=0.5, maxalpha=1.0):
 
29
    mincount = min(worddict.itervalues())
 
30
    maxcount = max(worddict.itervalues())
 
31
    weights = {}
 
32
    for k, v in worddict.iteritems():
 
33
        w = (v-mincount)/(maxcount-mincount)
 
34
        alpha = minalpha + (maxalpha-minalpha)*w
 
35
        size = minsize + (maxsize-minsize)*w
 
36
        weights[k] = (alpha, size)
 
37
    return weights
 
38
 
 
39
 
 
40
def tagcloud(worddict, n=10, minsize=25, maxsize=50, minalpha=0.5, maxalpha=1.0):
 
41
    from matplotlib import pyplot as plt
 
42
    import random
 
43
 
 
44
    worddict = wordfreq_to_weightsize(worddict, minsize, maxsize, minalpha, maxalpha)
 
45
 
 
46
    fig = plt.figure()
 
47
    ax = fig.add_subplot(111)
 
48
    ax.set_position([0.0,0.0,1.0,1.0])
 
49
    plt.xticks([])
 
50
    plt.yticks([])
 
51
 
 
52
    words = worddict.keys()
 
53
    alphas = [v[0] for v in worddict.values()]
 
54
    sizes = [v[1] for v in worddict.values()]
 
55
    items = zip(alphas, sizes, words)
 
56
    items.sort(reverse=True)
 
57
    for alpha, size, word in items[:n]:
 
58
        # xpos = random.normalvariate(0.5, 0.3)
 
59
        # ypos = random.normalvariate(0.5, 0.3)
 
60
        xpos = random.uniform(0.0,1.0)
 
61
        ypos = random.uniform(0.0,1.0)
 
62
        ax.text(xpos, ypos, word.lower(), alpha=alpha, fontsize=size)
 
63
    ax.autoscale_view()
 
64
    return ax
 
65
    
 
66
    
 
 
b'\\ No newline at end of file'