import math
class node():
def __init__(self):
self.num= 0 #节点的数值
self.name = None #节点的名字 比如 a b c
self.father = -1 #根节点
self.left_son = None #左孩子
self.right_son = None #右孩子
self.encode ="" #编码值
d={} #存读进来的字母
all = 0
pinglv={} #从来存计算好的频率 这里用来一会做平均码长的计算
#以下为读取文本模块
f = open("e","r")
temp=f.read()
temp.strip()
temp.lower() #把大写字母转换为小写字母
for i in temp:
if i.isalnum():
all=all+1
if i in d:
d[i] = d[i]+1
else:
d[i]=1
print(d)
new_d = list(sorted(d.items(),key=lambda x:x[1],reverse=True)) #逆序排列
print(new_d)
for i in new_d:
cal = i[1]
cal = cal/all
pinglv[i[0]]=cal
print(pinglv)
# for i in pinglv.items():
# print(i[1])
all_node=[]
num=0
for i in new_d:
temp_node = node()
temp_node.name = i[0]
temp_node.num = i[1]
num = i[1]+num
all_node.append(temp_node)
sign=0
while( sign!=num ):
left = all_node.pop()
right = all_node.pop()
father = node()
father.num = left.num + right.num
left.father = father
right.father = father
father.left_son = left
father. right_son = right
sign = father.num
all_node.append(father)
# print("排序")
all_node=sorted(all_node,key=lambda x:x.num,reverse=True)
# print("结果")
# for i in range(len(all_node)):
# print(all_node[i].name, all_node[i].num)
res = {}
now_encode=""
leafs = []
def pre(root):
if( root.right_son==None ):
# print("叶子节点")
# print(root.num)
leafs.append(root)
return
# print("当前节点:",root.num)
pre(root.left_son)
pre(root.right_son)
pre(all_node[0])
for i in range(len(leafs)):
# print("对于节点",leafs[i].num)
temp_ = leafs[i]
encode=" "
while( temp_.father!=-1 ):
# print( temp_.father.left_son.num )
if ( temp_ == temp_.father.left_son ):
encode = "1"+encode
else:
encode ="0"+ encode
temp_ = temp_.father
leafs[i].encode=encode
res_leaf = sorted(leafs,key=lambda x:len(x.encode))
print("编码结果")
for i in range(len(res_leaf)):
print(res_leaf[i].name,res_leaf[i].encode)
pingjunmashang=0
tt=0
for i in pinglv.items():
pingjunmashang = len(res_leaf[tt].encode) * i[1] + pingjunmashang
print("平均码长",pingjunmashang)
下面是我的那篇e的测试文档 如下
When I was ten I was suddenly confronted with the anguish of moving from the only home I had ever known.My whole life,brief as it was,had been spent in that big old house,gracefully touched with the laughter and tears of four generations.
When the final day came,I ran to the haven of the small back porch and sat alone,shuddering,as tears welled up from my heart.Suddenly I felt a hand rest on my shoulder.I looked up to see my grandfather."It isn’t easy,is it,Billy?" he said softly,sitting down on the steps beside me.
"Grandpa," I replied through my tears,"how can I ever say goodbye to you and all my friends?"
For a moment he just stared off into the apple trees."Goodbye is such a sad word," he said."It seems too final,too cold,for friends to use.We seem to have so many ways of saying goodbye and they all have one thing in common:sadness."
I continued to look into his face.He gently took my hand in his."Come with me,my friend," he whispered.
We walked,hand in hand,to his favorite place in the front yard,where a huge red rosebush sat conspicuously alone.
"What do you see here,Billy?" he asked.
I looked at the flowers,not knowing what to say,and then answered,"I see something soft and beautiful,Grandpa." [/size][/font]
Kneeling,he pulled me close."It isn’t just the roses that are beautiful,Billy.It’s that special place in your heart that makes them so."[/size][/font]
His eyes met mine again."Billy,I planted these roses a long,long time ago—before your mother was even a dream.I put them into the soil the day my first son was born.It was my way of saying thankyou to God.That boy’s name was Billy,just like yours.I used to watch him pick roses for his mother." I saw my grandfather’s tears.I had never seen him cry before.His voice became hoarse.
"One day a terrible war came,and my son,like so many sons,went away to fight a great evil.He and I walked to the train station together...Ten months later a telegram came.My son had died in some tiny village in Italy.All I could think of was that the last thing I said to him in his life was goodbye." Grandpa slowly stood up."Don’t ever say goodbye,Billy.Don’t ever give in to the sadness and the loneliness of that word.I want you to remember instead the joy and the happiness of those times when you first said hello to a friend.Take that special hello and lock it away within you—in that place in your heart where summer is an always-time.When you and your friends must part,I want you to reach deep within you and bring back that first hello."
A year and a half later,my grandfather became gravely ill.When he returned after several weeks in the hospital,he wanted his bed next to the window,where he could see his beloved rosebush.
Then the family was summoned,and I returned to the old house.It was decided that the oldest grandchildren would be allowed to say their goodbyes.
When it came to my turn,I noted how tired he looked.His eyes were closed and his breathing was slow and hard.I took his hand as gently as he had once taken mine.
"Hello,Grandpa," I whispered.His eyes slowly opened,"Hello,my friend," he said,with a brief smile.His eyes closed again and I moved on.
I was standing by his rosebush when an uncle came to tell me that my grandfather had died.Remembering Grandpa’s words,I reached deep within me for those special feelings that had made up our friendship.Suddenly,and truly,I knew what he had meant about never saying goodbye—about refusing to give in to sadness.