Python学习第六章

2018-12-09  本文已影响0人  赵一矛

组合数据类型概述

组合数据类型为多个同类型或不同类型数据提供的单一表示。组合数据类型分3类:序列类型,集合类型和映射类型。


元组(tuple)

元组是序列类型中比较特殊的类型,因为它一旦创建就不能修改。元组类型在表达固定数据项、函数多返回值、多变量同步赋值、循环遍历等情况下十分有用。
Python中元祖采用逗号或圆括号(可选)来表示。


集合类型

集合是无序组合,它没有索引和位置的概念,不能分片,集合中元素可以动态增加或删除。集合用大括号({})表示,可以用赋值语句生成一个集合。



因为集合元素是独一无二的,使用集合类型可以过滤掉重复的元素。

from math import sqrt
def getNum():
    nums=[]
    isNumber=input("请输入数字(直接输入回车退出):")
    while isNumber  != "":
        nums.append(eval(isNumber))
        isNumber=input("请输入数字(直接输入回车退出):")
    return nums
def mean(numbers): #计算平均数
    s=0.0
    for num in numbers:
        s=s+num
    return s/len(numbers)
def dev(numbers,mean): #计算方差
    sdev=0.0
    for num in numbers:
        sdev=sdev+(num-mean)**2
    return sqrt(sdev/(len(numbers)-1))
def median(numbers): #求中位数
    sorted(numbers)
    size=len(numbers)
    if size%2==0:
        med=(numbers[size//2-1]+numbers[size//2])/2
    else:
        med=(numbers[size//2])
    return med

n=getNum()
m=mean(n)
print("平均数{},方差{:.2},中位数{}".format(m,dev(n,m),median(n)))

字典类型和操作

字典是包含0个或多个键值对的集合,没有长度限制,可以根据键索引值的内容。

jieba库的使用

jieba库是Python中一个重要的第三方中文分词函数库。
jieba库是第三方库,不是python安装包自带的,因此,需要通过pip指令安装。
注:pip是python的内部命令,需要通过命令行执行,执行pip -h命令可以将列出pip常用的子命令,注意:不要在IDEL环境下运行pip程序。
python版本高一点的话pip是以及安装好的。
pip install jieba安装jieba第三方库

安装成功
jieba库的分词原理是利用一个中文词库,将待分组的内容与分词词库进行比对,通过图结构和动态规划的方法找到最大概率的词组,除了分词,jieba库还提供了增加自定义中文单词的功能。
jieba库支持三种分词模式:

文本词频统计

输入:从文件中读取一篇文章
处理:采用字典数据结构统计词语出现的次数
输出:文章中最常出现的10个单词及出现次数。
hamlet文本

This is the sad story of Hamlet, young Prince of Denmark, whose father died two months before the story begins. Hamlet´ s father was King of Denmark and Hamlet was his only son. The king died a strange death while he was sleeping in the garden of his castle. It was believed that he had been bitten to death by a poisonous snake. He was such a wise and kind king that he was loved by all the people in the nation. His son, Hamlet, of course, loved him far more than anyone else in the world. 
Hamlet was so sad and sorrowful that he never stopped wearing black clothes. There was something else which made Hamlet even sadder. His mother, Gertrude, married Hamlet´ s uncle, Claudius, who was a brother of the late king. After Hamlet´ s father died, Claudius became King of Denmark and married Gertrude. Young Hamlet did not like him because he was not as wise and kind as his father. He was a man of unkindly character. Hamlet did not in the least want his mother to marry such a man. He became angry with both of them and came to despise his mother as well as his uncle. 

The bell of the castle was ringing. It was exactly midnight. Suddenly a ghost in the form of the late king appeared in the darkness. It looked pale and sad. Looking at the ghost, the two guards of the castle and Horatio, Hamlet´ s best friend, were surprised and terrified. They wondered if something bad was going to happen in Denmark. They decided to tell their prince what they had seen . 
The next day they went to Hamlet and told him that they had seen the ghost of King Hamlet. Hamlet doubted it at first, but wanted to make sure himself. He asked them to take him to see the ghost that night. They agreed. 
Late at night Hamlet, Horatio and one of the guards went to the top of the walls. It was very cold and dark there. Some time after they got there, the ghost in armor suddenly appeared out of the darkness. As his friends had told him, Hamlet saw that the ghost was exactly like his dead father. 
He called out, "King, Father! Why did you come here out of the grave?" 
The ghost did not answer him, but looked at him sadly and made a sign for him to follow. His friends did not want to let Hamlet follow the ghost because they thought it might be an evil spirit and do something badto him. But he did follow the ghost. While Hamlet and the ghost walked away into the darkness, his friends had to wait anxiously there worrying about his safe return . 
At the end of the walls of the castle the ghost stopped and began to talk to Hamlet, "I am the ghost of your father. I wanted to rule Denmark peacefully until you grew up and became king after me. But two months ago, while I was sleeping in the beautiful garden of the castle, my brother Claudius came and put poison into my ear. I was instantly killed. Hamlet! Be brave and kill him for me. But never kill or hurt my wife, for she is your mother. Let her repent for what she has done. That is enough for her. What I have told you is true. I tell you again. I was not killed by a poisonous snake, but by my brother Claudius. Never forget what I have told you, my dear son. Good-bye, Hamlet!" 
Then the ghost disappeared into the mist of the dark sky. Upon hearing this, Hamlet became excited and was even more furious with Claudius and his mother. He made up his mind to kill his uncle and let his mother repent for her sins. 

Hamlet´s friends were anxious about him and came to look for him. They found Hamlet kneeling down and looking up at the dark sky praying to God. Hamlet noticed them coming to him. He stood up and sincerely asked them not to tell anyone what had happened that night. They all agreed and made a firm promise not to tell anyone about it, swearing on Hamlet´ s sword. 
That very night Hamlet decided to pretend that he had gone mad in order to have a better chance to kill Claudius. He decided not to tell his plan to any of his friends except Horatio . 
Since Hamlet saw the ghost, he had often thought of his dead father and of his promise to the ghost. He became sadder each day. He was not a young, merry prince as he used to be. Before his father´ s death, he was interested in many things, such as books, art, music and plays. But now he gave them all up. To everyone, he seemed to act very strangely. He became rude to everyone in the castle and behaved like a mad man. 
He hardly ever spoke to Ophelia , a beautiful lady whom he had deeply loved. Before, they would talk happily and take walks in the woods near the castle. He would talk to her so sweetly and gently that Ophelia was deeply in love with him. But now he was quite different. Therefore, Polonius, Ophelia´ s father, did not want his daughter to love Hamlet anymore because of his strange behavior. 

One day Hamlet came to Ophelia, who was knitting in her room, and spoke wildly to her. He appeared half-naked, wearing a dirty shirt with no hat on his head. She gave back all the letters and valuable rings that she had received from Hamlet. 
"I will not meet you anymore," she said to him. Hamlet left her, feeling even more miserable. 
She told her father everything that had occurred in her room. When Polonius heard this from his daughter, he believed he knew what had made Hamlet go mad. He thought that Hamlet had gone mad because of his love for Ophelia . Polonius went to Claudius and Gertrude to let them know what caused Hamlet´s madness. He told them that the love affair between Hamlet and Ophelia was the true cause of his madness. 
Claudius always doubted what he heard from his men. He commanded two men who used to be Hamlet´ s friends when they were children to find out the true reason why he had been acting so strangely recently. He also asked Polonius to arrange an unexpected meeting of the two lovers so that they could carefully observe Hamlet´ s behavior. 

Hamlet´s two old friends met him when he was saying some strange things to himself alone in the hall of the castle. They begged him to tell them the true cause of his madness. But he would not tell them anything, and instead made fools of them. 
One day when Hamlet was unhappy and worried by the memory of the ghost and the promise he had made, a group of actors came to visit him. They were the same players that Hamlet used to enjoy seeing. He welcomed them. Then they acted a short play for him. 
It was a sad story about a good king who was poisoned to death by his brother. And this man became king and married the queen. They played it so well, with tears in their eyes, that the scene seemed real. While Hamlet was watching them, he felt very angry with himself. He said to himself, "Those players can cry for the sad king whom they have never met. But in my case I have done nothing at all for my poor father who was killed by my uncle Claudius. What a coward I am!" 
When the play was over, he thought of a good plan. He decided to have them play it once again in front of the king and queen the next day. He also asked them to add a few lines of his own to the play so that he could make the play more like what had happened to his father. Hamlet said to himself, "If Claudius is really guilty, his face will turn pale while he is watching the play. Then I will know that what the ghost told me is true. I will watch his face very carefully." 
He told his plan to Horatio, his best friend in the castle, and also asked him to watch the king´ s face with the greatest care. 
Hamlet went to the king and queen to tell them that he would like to invite them to a play the next evening. They agreed to see the play. They hoped that Hamlet was at last getting better and would come to accept them as his father and mother. He said good night to Claudius and Gertrude, pretending that he was happy that night. 
On his way back to his own room, he met Ophelia, who looked so sad and unhappy in the hall. The king and Polonius were hiding behind the curtains of the hall, trying to listen to their conversation. 
Hamlet said to Ophelia, "I don´ t love you anymore. We are all dirty animals on this earth. Ophelia, you are one of these dirty ones, too. Go to a nunnery. Go away right now, you dirty woman!" 
Ophelia was too surprised at his words to say anything to him. It was such a strange and mad thing to say. Polonius thought his guess was right. But the king still doubted Hamlet´ s madness. 
The king, the queen and Polonius entered a large room where the play was to be shown to the whole court. The king sat with the queen. Hamlet sat by the side of Ophelia. Horatio sat facing the king in order to watch him carefully. 

The play began. In the play the king and queen were talking on the bench in the beautiful garden. The queen said to the king, "I will love you forever. I will never marry another man if you should die before me. Only women that kill their husbands marry again. " The king in the play was very glad to hear this. As the king fell asleep, the queen left him alone. Just after she left, the king´s brother came near the sleeping king and poured a deadly poison into his ear. He was soon killed by this cunning brother who had long wanted to become king and marry the queen. 
Seeing this scene, Claudius turned pale and became very angry. He shouted, "Stop the play at once. " He stood up and went out of the room with the queen. 
Horatio and Hamlet saw the king show every sign of fear and anger. Hamlet was now quite sure that the ghost had told him the truth. He himself became excited and firmly decided to revenge his father as soon as he could. When the queen came back into her room, she was very worried about her son, who had made the king furious. She wanted to know why Hamlet asked the group of players to show such a disgraceful play before the king. She sent for Hamlet. 

Hamlet hurriedly walked to her room where she was uneasily waiting for him. On the way to his mother´ s room, Hamlet saw Claudius kneeling down to pray in his room. He thought he could kill him right then. But he did not do it. He said to himself, "If I kill him when he is praying to God, he will not go to hell. I had better kill him when he is angry or doing something bad. Then he is sure to go to hell. " So he stopped thinking of killing Claudius for the moment. 
Hamlet did not know that the doubting king had commanded Polonius to hide behind the curtains in the queen´ s room so that he could see what might happen there. As soon as Hamlet came into her room, his mother began to scold him for what he had done to the king. She said angrily, "You have made your father very angry. You must beg his pardon." 
Hamlet would not listen to her, but answered back. He said, "It is you who are to blame. You married that unkind and unkingly uncle of mine so soon after my father´ s death. 
You should be ashamed of your deed. I will never accept him as my father. He does not deserve to be King of Denmark. I will tell you again. It is not I but you and that dirty Claudius that should repent." 

The queen became excited at hearing this and tried to run out of the room. Hamlet grabbed her by the wrist so roughly that she was frightened and cried out, "Are you going to kill me? Help! Help!" 
On hearing the queen´ s cry for help, Polonius, who was hiding behind the curtains, also cried, "Hamlet! Don´t hurt the queen. Someone! Help the queen!" 
Hamlet shouted, "What is that? A rat?" Thinking that it was Claudius, he drew his sword and rushed to the curtains. The man behind the curtains fell dead. Hamlet was shocked to see the dead body of Polonius, Ophelia´ s father, there. 
"Oh, Hamlet. What a cruel thing you have done!" cried the queen in terror. 
Hamlet answered, "No, it is not I but you that have done a cruel thing." 
Then suddenly, the ghost of his father appeared before them. His mother could neither see nor hear it. It said, "Hamlet, do not harm the queen, because she is your mother; kill Claudius as quickly as possible. Now, Hamlet, get out of this room!" 
"Yes, I will, Father," said Hamlet to the ghost. The queen thought that Hamlet was really mad. Hamlet obeyed his father´s advice and left the queen and the dead body of Polonius . 
def getText():
        txt=open("hamlet.txt","r").read()
        txt=txt.lower() #将字母全部变为小写,排除原文中大小写差异对词频统计的干扰
        for ch in '!"#$%&()*+,-./:;<=>?@[//]^_`{|}~':
            txt=txt.replace(ch," ") #将文本中特殊字符替换为空格
        return txt

hamletTxt=getText()
words=hamletTxt.split()
counts={}
for word in words:
    counts[word]=counts.get(word,0)+1 #如果word在counts中,则返回word对应的值,如果不在的话,则返回0
items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
for i in range(10):
    word,count=items[i]
    print("{0:<10}{1:>5}".format(word,count))

根据结果可以看出多数词是冠词,代词、连接词等语法词,并不能代表文章的含义,可以采用集合类型构建一个排除词汇库excludes

excludes=['the','he','she','of','and','you','my','i','in','a']
def getText():
        txt=open("hamlet.txt","r").read()
        txt=txt.lower() #将字母全部变为小写,排除原文中大小写差异对词频统计的干扰
        for ch in '!"#$%&()*+,-./:;<=>?@[//]^_`{|}~':
            txt=txt.replace(ch," ") #将文本中特殊字符替换为空格
        return txt

hamletTxt=getText()
words=hamletTxt.split()
counts={}
for word in words:
    counts[word]=counts.get(word,0)+1 #如果word在counts中,则返回word对应的值,如果不在的话,则返回0
for word in excludes:
    del(counts[word])
items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
for i in range(10):
    word,count=items[i]
    print("{0:<10}{1:>5}".format(word,count))

python之禅

Python之禅介绍了编写好代码的基本原则


上一篇 下一篇

猜你喜欢

热点阅读