bzr branch
http://gegoxaren.bato24.eu/bzr/%2Bjunk/pygooglechart-py3k
54
by gak
Added some example helpers for MapChart |
1 |
class CountryCodes: |
2 |
''' |
|
3 |
This is just a helper to generate useful data files. It isn't directly used
|
|
4 |
in these examples.
|
|
5 |
'''
|
|
6 |
||
7 |
def __init__(self): |
|
8 |
self.parse_codes_data() |
|
9 |
||
10 |
def parse_codes_data(self): |
|
11 |
lines = open('iso3166-1-a2.txt', 'rb').read().split('\n') |
|
12 |
self.codes = dict([ a.split(' ', 1) for a in lines[:-1] ]) |
|
13 |
||
14 |
def get_country_code_from_name(self, guess_name): |
|
15 |
best_score = 100 |
|
16 |
best_code = None |
|
17 |
for code, name in self.codes.items(): |
|
18 |
score = self.levenshtein(guess_name, name) |
|
19 |
if score < best_score: |
|
20 |
best_score = score |
|
21 |
best_code = code |
|
22 |
return best_code |
|
23 |
||
24 |
def levenshtein(self, a, b): |
|
25 |
"Calculates the Levenshtein distance between a and b."
|
|
26 |
n, m = len(a), len(b) |
|
27 |
if n > m: |
|
28 |
# Make sure n <= m, to use O(min(n,m)) space
|
|
29 |
a,b = b,a |
|
30 |
n,m = m,n |
|
31 |
||
32 |
current = range(n+1) |
|
33 |
for i in range(1,m+1): |
|
34 |
previous, current = current, [i]+[0]*n |
|
35 |
for j in range(1,n+1): |
|
36 |
add, delete = previous[j]+1, current[j-1]+1 |
|
37 |
change = previous[j-1] |
|
38 |
if a[j-1] != b[i-1]: |
|
39 |
change = change + 1 |
|
40 |
current[j] = min(add, delete, change) |
|
41 |
||
42 |
return current[n] |
|
43 |