7. Python字典數據

dictionaryName[key] = value

1. 使用大括號創建字典

  student = { “203-2012-002”:“Peter”,“203-2016-024”:“John”}

2. 使用中括號添加字典值

  student  ["202-2016-125"] = "Sunan"

3. 使用鍵查詢字典中的值

  student ["202-2016-125"]

  'Sunan'

若輸入的鍵不存在,則返回錯誤信息

4. 使用 del dictionaryName[key] 刪除字典中的值

  del student ["202-2016-125"]

5. 使用 for key in dictionaryName:

                   print (key+":"+str(diationaryName[key])) 通過字典的鍵遍歷字典

字典的遍歷:

  5.1 遍歷字典的鍵key:for key in dictionaryName.keys():print(key)

  5.2 遍歷字典的值value:for value in dictionaryName.values():print(value)

  5.3 遍歷字典的項:for item in dictionaryName.items():print(item)

  5.4 遍歷字典的key-value:for item,value in adict.items():print(item,value)

6. 使用 in 或者 not in 判斷是否一個鍵在字典中

  “202-2016-125” in student

  True

  “202-2016-120” in student

  False

7. 字典的標準操作符:-,<,>,<=,>=,==,!=,and,or,not

  d1 = {“red”:41,"blue":3}

  d2 = {"blue":3,“red”:41}

  d1 == d2

  True

8. 字典中的方法


9. 實例——詞頻統計

步驟:

(1)輸入英文文章

(2)建立用於詞頻計算的空字典

(3)對文本的每一行計算詞頻

(4)從字典中獲取數據對到列表中

(5)對列表中的數據對交換位置,並從大到小進行排列

(6)輸出結果

(7)用Turtle庫繪製統計詞頻結果圖表

代碼如下:

import turtle

#全局變量
data=[]     #單詞頻率數組—作爲y軸數據
words=[]    #單詞詞組—作爲x軸數據
yScale=6    #y軸顯示放大倍數—可以根據詞頻數量進行調節
xScale=50   #x軸顯示放大倍數—可以根據count數量進行調節

      

###################### 繪製圖像函數組 ####################

#從點(x1,y1)到(x2,y2)繪製線段
def drawLine(t,x1,y1,x2,y2):
    t.penup()
    t.goto(x1,y1)
    t.pendown()
    t.goto(x2,y2)

#在座標(x,y)處寫文字
def drawText(t,x,y,text):
    t.penup()
    t.goto(x,y)
    t.pendown()
    t.write(text)

#繪製一個柱體
def drawRectangle(t,x,y):
    x=x*xScale
    y=y*yScale    #放大倍數顯示
    drawLine(t,x-5,0,x-5,y)
    drawLine(t,x-5,y,x+5,y)
    drawLine(t,x+5,y,x+5,0)
    drawLine(t,x+5,0,x-5,0)

#繪製多個柱體
def drawBar(t,count):
    for i in range(count):
        drawRectangle(t,i+1,data[i])
        
#完整的統計圖繪製
def drawGraph(t,count):
    #繪製x/y軸線
    drawLine(t,0,0,360,0)
    drawLine(t,0,300,0,0)

    #x軸:座標及描述
    for x in range(count):
        x=x+1   #向右移一位,爲了不畫在原點上
        drawText(t,x*xScale-4,-20,(words[x-1]))
        drawText(t,x*xScale-4,data[x-1]*yScale+10,data[x-1])
        drawBar(t,count)
        
###################### 輔助程序 ####################

#對文本的每一行計算詞頻的函數
def processLine(line,wordCounts):
    #空格替換標點符號
    line=replacePunctuations(line)
    #從每一行獲取每個詞
    words=line.split()
    for word in words:
        if word in wordCounts:
            wordCounts[word]+=1
        else:
            wordCounts[word]=1

#空格替換標點的函數
def replacePunctuations(line):
    for ch in line:
        if ch in "~!@#$%^&*()_-+=<>?,./:;{}[]|\'""":
            line=line.replace(ch," ")
    return line
        
###################### 主程序 ####################

def main():
    #用戶輸入一個文件名
    filename=input("enter a filename:").strip()  #strip()函數刪除掉開頭結尾處的空格
    infile=open(filename,"r")

    #建立用於計算詞頻的空字典
    wordCounts={}
    for line in infile:
        processLine(line.lower(),wordCounts)   #lower()將所有大寫字母變成小寫,方便排序

    #從字典中獲取數據對
    pairs=list(wordCounts.items())  
     
    #列表中的數據對交換位置,數據對排序
    items = [[x,y]for (y,x)in pairs] 
    items.sort()    #sort()函數從小到大排序    
    count=len(items)
    
    #輸出count個數詞頻結果
    for i in range(count - 1, -1, -1):    
        print(items[i][1]+"\t"+str(items[i][0]))
        data.append(items[i][0])
        words.append(items[i][1])    

    infile.close()

    #根據詞頻結果繪製柱狀圖
    turtle.title('詞頻結果柱狀圖')
    turtle.setup(900,750,0,0)
    t=turtle.Turtle()   #初始化畫筆
    t.hideturtle()
    t.width(3)
    drawGraph(t,count)

#調用main()函數
if __name__=='__main__':
    main()

############################################################
結果:

enter a filename:111.txt
china	4
is	3
a	3
big	2
country	1



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章