Python - 霍夫曼位压缩

时间:2016-05-10 14:47:10

标签: python list nodes

我需要帮助。我做了一个霍夫曼压缩程序。例如,我输入"谷歌",我可以像这样打印:

Character | Frequency | Huffman Code
------------------------------------
'g'       |         2 |           0
'o'       |         2 |          11
'l'       |         1 |         101
'e'       |         1 |         100

我还需要打印组合位,所以如果我使用它将是:

011101100

哪个是错的,因为据我所知,霍夫曼压缩应该是:

011110101100

所以我的输出应该是:

Character | Frequency | Huffman Code
------------------------------------
'g'       |         2 |           0
'o'       |         2 |          11
'o'       |         2 |          11
'g'       |         2 |           0
'l'       |         1 |         101
'e'       |         1 |         100

基本上我需要根据输入内容显示它。所以,如果我输入" test"它还应该用相应的位垂直打印测试,因为我只是附加位并显示它们。我该如何实现这一目标?这是打印部分:

freq = {}
for c in word:
    if c in freq:
        freq[c] += 1
    else:
        freq[c] = 1

freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)

if check:
    print (" Char | Freq ")
    for key, c in freq:
        print (" %4r | %d" % (key, c))

nodes = freq

while len(nodes) > 1:
    key1, c1 = nodes[-1]
    key2, c2 = nodes[-2]
    nodes = nodes[:-2]
    node = NodeTree(key1, key2)
    nodes.append((node, c1 + c2))
    nodes = sorted(nodes, key=lambda x: x[1], reverse=True)

if check:
    print ("left: %s" % nodes[0][0].nodes()[0])
    print ("right: %s" % nodes[0][0].nodes()[1])

huffmanCode = huffman(nodes[0][0])

print ("\n")
print (" Character | Frequency  | Huffman code ")
print ("---------------------------------------")

for char, frequency in freq:
   print (" %-9r | %10d | %12s" % (char, frequency, huffmanCode[char]))

P.S。我知道我不应该对它们进行分类我会删除分类部分,不用担心

0 个答案:

没有答案