1 #CalHamletV1.py 2 def getText(): #定義函數讀取文件 3 txt = open("hamlet.txt","r").read() 4 txt = txt.lower() #將所有字符轉換為小寫 5 for ch in '!@#$%^&*(_)-+=\\[]}{|;:\'\"`~,<.>?/': 6 txt = txt.replace(ch, " ") #將所有特殊符號用空格替代 7 return txt 8 hamletTxt = getText() 9 words = hamletTxt.split() #用空格分隔文本並生成列表 10 counts = {} 11 for word in words: 12 counts[word]=counts.get(word,0)+1 #生成字典的內容:若該鍵存在則取其值並+1 13 items=list(counts.items()) #返回所有鍵值對信息,生成列表 14 items.sort(key=lambda x:x[1],reverse=True) #對列表反排序:降序排列 15 for i in range(10): 16 word, count = items[i] 17 print("{0:<10}{1:>5}".format(word, count)) #打印前十個元素 18 19 #print(items[:10])
#結果如下:
下面這是老師視頻課件里的代碼和結果:
輸出的結果不一致,因為上面特殊字符的時候使用了兩個轉義符“\”.