當前位置:成語大全網 - 新華字典 - 加急用Python統計每個單詞出現的個數,具體要求如圖?

加急用Python統計每個單詞出現的個數,具體要求如圖?

#2019/12/26/18:24

def getText():

txt=open(r'D:\第十題.txt').read()

#打開文件

txt=txt.lower()#將字母全部轉化為小寫

for ch in ',-.()':#去掉特殊符號

txt=txt.replace(ch,"")#將特殊符號替換為空格

return txt

Txt=getText()#讀取文件

words=Txt.split()#分隔開

counts={}#創建字典

for word in words:

counts[word]=counts.get(word,0)+1

items=list(counts.items())

items.sort(key=lambda x:x[1],reverse=True)

#從大到小排序

for i in range (20):

print(items[i])