# 文章單字統計 ## 單字統計 * 做一個統計文章單字的程式 * 單字大小寫視為同個單字 * 比較級、最高級、過去分詞、過去式視為不同單字 * 刪除特殊符號如下 「 , 」 逗號 「 . 」 句號 「 ; 」 分號 「 ! 」 驚嘆號 「 ? 」問號 「 : 」 冒號 「 ” 」雙引號 、「 ’ 」單引號 「 't 」 、「 n't 」 、 「 'll 」、 「 'd 」、 「 've 」、 「 're 」、 「 's 」、 「 'm 」等...縮寫 * 列出出現頻率前十名 ## 架構 ### 1.把文章做成list(串列) 因為在每個英文單字中間都有空格,所以我們可以利用這個空格,將一連串的文章切割成一個個串列。 ### 2.排序文章單字(由a~z) 讓相同但獨立的單字擠在一起 ### 3.全部做成小寫並刪除特殊符號 ### 4.計算同個的單字數量並做成串列 一個是紀錄單字的種類 一個是紀錄相同單字的數量 ### 5.把單字和對應的數量做成Dictionary(字典) 等等比較好排列 ### 6.排列Dictionary,由數量多往數量少 等等比較好比較 ### 7.比較並列出前10名多的單字 ## 函數介紹 ### 1.輸入並切割文章做成list(串列) ``` python = list(map(type,input(output).split(x))) ``` ##### map函數+split分割函數 * type輸入想儲存入list串列的型態 ex.若想使用int整數型態儲存 則不能輸入文字(str) * output輸入提示字元 ex.使用冒號來提示用戶輸入 * x輸入要用什麼分割 ex.split(" ")就是用空格分割、split("123")則是中間有連續的123就分割 ### 2.排列list(串列) ``` python = xlist.sort() #xlist.sort(cmp=None, key=None, reverse=False) ``` 這會直接幫你把xlist由小排到大,由a排到z(按照ASCII 數字順序) * cmp=參數 * key=比較的參數 * reverse: True由大排到小 False由小排到大(預設) >補充:sort與sorted的區別 >sort會讓原本的串列改變 而sorted則是不改變的情況下排序 ex.輸出使用sorted不會讓原本的串列改變順序 >sort和sorted適用於串列 而字典只能使用sorted ### 3.讓單字全部變小寫 ``` python = x.lower() ```` * x - 單字 這會直接幫你把x全部變成小寫 ### 3.刪除單字中的特殊符號 ``` python = str.replace(old,new,times) ``` * old - 要替代的特殊符號 * new - 替代成什麼(可以沒有任何字串符號) * times - 最多替代幾次(可省略) 這會直接幫你把單字中想替換掉的old替換成新的new ### 4.增加單字數量 ``` python = xlist.append(word) ``` * 在xlist中增加一個單字 ### 5.把紀錄單字和紀錄單字數量的list(串列)混合成Dictionary(字典) ``` python = dict(zip(alist,blist)) ``` * 混和alist和blist * alist為key * blist為value ### 6.用數量排序Dictionary(字典 ``` python = sorted(xdict.items(), key=lambda y:(-y[1],y[0]) ``` #### lambda 函數 ``` python= def square(x): return x**2 print(square(3)) ``` 會等同於 ``` python= square=lambda x : x**2 print(square(3)) ``` #### lambda 函數排序字典 ``` python = key = lambda #呼叫lambda函數 ``` >把值由小排到大 >key 代表 排序的值 ``` y : (-y[1],y[0]) ``` > y 代表著字典的變數, y[1]則代表 ```xdict.items()```字典中的value > >而加上負號表示規則相反 --- > 由大到小 > > >而y[0],則是要求程式在將單字出現頻率排序好後,也將同出現次數的單字依ACSII Code 碼排序 (數子-a~z) #### 串列排序 ``` python= xlist=[1,5,3,4,2] bowl=0 for i in len(xlist): for u in len(xlist): if xlist[u] < xlist[i] : bowl=xlist[i] xlist[i]=xlist[u] xlist[u]=bowl ``` * xlist ≈ xdict.items() ## 完成程式碼 ``` python= article=list(map(str,input().split(" "))) #map函數+split函數 article.sort() #sort排列 delete=[',','.','?','!',':',';','\'s','\'t','n\'t','\'ll','\'d','\"','\'','\'re','\'ve','\'m'] #要刪除的字元 word=[] #儲存單字種類 num=[] #儲存單字數量 x=-1 for i in article: i=i.lower() #變成小寫 for u in delete: i=i.replace(u,"") #刪除字元 if i not in word: x+=1 word.append(i) #增加單字種類 num.append(1) #設定單字數量(1) else: num[x]+=1 #增加單字數量 artdict=dict(zip(word,num)) #做成Dictionary artdict=sorted(artdict.items(), key=lambda y:(-y[1],y[0]) #排序 print('前十名為:') for i in range(10): print(f"第{i+1}名:{artdict[i][0]} {artdict[i][1]}個") ```