adict={} x=input().lower() #把單詞大寫字母改為小寫字母 for i in x:if i in [',','.',"'",'"','!']:x=x[:x.index(i)]+x[x.index(i)+1:] #把句子中的非字母字符用切片操作刪掉 aset=set(x.split(' ')) #集合的好處在于不重復 alst=x.split(' ') for n in aset:tempdict={n:alst.count(n)}adict.update(tempdict) #字典的update方法,把tempdict內容添加到adict里面 sorted(adict) #排序 for w in adict:print(w,adict[w])
?第五行也可以用字符串的replace方法
x=x.replace(i,' ')
倒三行的排序,優化成:先按照詞頻排序,如果詞頻相同,則按照詞語排序(ASCII)
lst=sorted(adict.items(),key=lambda x:(x[1],x[0]))
#最終解答: adict={} x=input().lower() for i in x:if i in [',','.',"'",'"','!']:x=x[:x.index(i)]+x[x.index(i)+1:] aset=set(x.split()) alst=x.split(' ') for n in aset:tempdict={n:alst.count(n)}adict.update(tempdict) lst=sorted(adict.items(),key=lambda x:(x[1],x[0])) for w in lst:print(w[0],w[1])
?