txt = input('请输入中文:')
tem = txt.split()#得到列表
d = {}
for i in range(len(tem)):
d[tem[i]] = d.get(tem[i],0) + 1
ls = list(d.items())
print(ls)
ls.sort(key = lambda x :x[1] , reverse= True)
for k in ls:
print('{name}:{num}'.format(name = k[0],num = k[1]))
逐行解释代码:
1、首先用 input 函数得到传入的字符串,并复制到txt中,txt = ‘综合 理工 综合 理工 文史’
2、现在得到的字符串并不能做词频统计,需要用split 函数将其切割,得到一个列表tem
3、建立一个字典d
4、运用 for 函数历遍整个tem列表,此时运用了d [ ]与d.get ,d [tem[ i ] ]的意思为:在d字典中寻找key为tem[ i ]的value,如果找不到,则创建一个新的值键对;之后运用d.get[ tem[ i ], 0] + 1,意为得到key 为tem[i] 的value,找不到则赋值为0,然后再加上1;通过这种方法统计词频。
5、运用list方法与items方法得到以保护值键对为元组的列表,例如:[('综合', 3), ('理工', 3), ('文科', 2)]
6、利用sort函数,sort函数包含两个变量,第一个key为排序依据,reverse = True表示降序排列。
7、format字符串方法,不再赘述。