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])