【字典2】Python

【字典2】阅读下面这段文字
Python includes two operations for sorting. The method sort() in the built-in list data type
rearranges the items in the underlying list into ascending order, much like merge.sort(). In
contrast, the built-in function sorted() leaves the underlying list alone; instead,
 it returns a new list containing the items in ascending order.
 
理解上述文字后,并定义成字符串,对其进行词频统计,再按照词频和字典顺序排序
提示
	1、词频是主关键字,字典顺序是次关键字 
	2、字典顺序不考虑大小写,可以使用字符串的lower方法
txt = "Python includes two operations for sorting. The method sort() in the built-in list data typerearranges the " \
        "items in the underlying list into ascending order, much like merge.sort(). Incontrast, the built-in function " \
        "sorted() leaves the underlying list alone; instead, it returns a new list containing the items in ascending " \
        "orderfor"
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(10):
    word,count = items[i]
    print("{0:<10}{1:>5}".format(word,count))

s = "Python includes two operations for sorting. The method sort() in the built-in list data typerearranges the " \
        "items in the underlying list into ascending order, much like merge.sort(). Incontrast, the built-in function " \
        "sorted() leaves the underlying list alone; instead, it returns a new list containing the items in ascending " \
        "orderfor"

s=s.lower()
sp=['.',',','(',')',';']
for i in sp:
    s=s.replace(i,"")
sList = s.split()
#统计词频个数
dic={}
for i in sList:
    dic[i]=dic.get(i,0)+1

#按照题目要求进行排序
    d=sorted(dic.items(),key=lambda kv:(-kv[1],kv[0]))
print(d)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值