使用二进制数字按降序编码字母

时间:2014-11-29 19:40:30

标签: python

这是python中的代码,这段代码按降序排列字母表,现在我想用0和下一个字母表编码每个字母表1,然后是00,01,10,11,000,001等等。请帮帮我。

from collections import defaultdict
import string
text ='intalks is an organization comprised of passionate students'.lower().translate(None,string.punctuation+' ')
c = defaultdict(int)
c.update({letter:0 for letter in string.lowercase[:26]})
for letter in text:
        c[letter] += 1


for letter,freq in sorted(c.iteritems(),key=lambda (l,f): (-f,l)):
        print freq, letter 

1 个答案:

答案 0 :(得分:0)

该计划是: -

from collections import defaultdict
import string
text ='intalks is an organization comprised of passionate students'.lower().translate(None,string.punctuation+' ')
c = defaultdict(int)
c.update({letter:0 for letter in string.lowercase[:26]})
for letter in text:
        c[letter] += 1


def getbin(foo):
    if len(set(a))==1 and a[0] == '1':
        return '0'*(len(a)+1)
    else:
        return (("{0:0"+str(len(a))+"b}").format(int (a,2)+1)).zfill(len(a))


a = '0'


for letter,freq in sorted(c.iteritems(),key = lambda (l,f) : f, reverse = True):
    print letter,a,freq
    a = getbin(a)

输出结果为: -

s 0 7
a 1 6
i 00 6
n 01 6
o 10 5
t 11 5
e 000 3
d 001 2
p 010 2
r 011 2
c 100 1
g 101 1
f 110 1
k 111 1
m 0000 1
l 0001 1
u 0010 1
z 0011 1
b 0100 0
h 0101 0
j 0110 0
q 0111 0
w 1000 0
v 1001 0
y 1010 0
x 1011 0