Last active
December 13, 2015 17:58
-
-
Save lqez/4951310 to your computer and use it in GitHub Desktop.
Dict <-> String parser for NICE - KOREA INFORMATION SERVICE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Dict <-> String parser for NICE - KOREA INFORMATION SERVICE (sigh) | |
# | |
# [email protected] | |
# | |
from itertools import izip | |
def encode(d): | |
res = [] | |
for key in d.keys(): | |
res.append('%d:%s%d:%s' % (len(key), key, len(str(d[key])), str(d[key]))) | |
return ''.join(res) | |
def decode(s): | |
tokens = [] | |
try: | |
while s is not '': | |
t = s.split(':', 1) | |
s = s[len(t[0])+1:] | |
tokens.append(s[:int(t[0])]) | |
s = s[int(t[0]):] | |
except: | |
return None | |
i = iter(tokens) | |
return dict(izip(i, i)) | |
def test(): | |
s = '3:foo3:bar' | |
d = {'foo':'bar'} | |
assert(s == encode(d)) | |
assert(d == decode(s)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment