对文中出现的句号,逗号和感叹号做了相应的处理
sorted排序函数用法:
按照value值降序排列:
sorted(dict.items(),key=lambda k:k[1],reverse=True)
按照value值升序排序:
sorted(dict.items(),key=lambda k:k[1],reverse=False)或者sorted(dict.items(),key=lambda k:k[1])
按照key值降序排列:
sorted(dict.items(),key=lambda k:k[0],reverse=True)
按照key值升序排列:
sorted(dict.items(),key=lambda k:k[0])或者sorted(dict.items(),key=lambda k:k[0],reverse=False)
#-*- coding: utf-8 -*- file_object=open("english") dict={} for line in file_object: line=line.replace(","," ") line=line.replace("."," ") line=line.replace("!"," ") strs= line.split(); for str in strs: if dict.has_key(str): dict[str]+=1 else: dict[str]=1 result=sorted(dict.items(),key=lambda k:k[1],reverse=True) print result