可以结合我主页里面的那个用来记忆四级单词的程序改造为统计单词出现的频率
class Solution:
def topKFrequentWords(self,words):
dict = {}
res = []
for word in words:
if word not in dict:
dict[word] = 1
else:
dict[word] += 1
#这里是将字典进行排序
#这样就是从大到小的排序
#sorted_d = sorted(dict.items(),key=lambda x:x[1],reverse=True)
#这样就是从小到大的排序
sorted_d = sorted(dict.items(), key=lambda x: x[1])
print(sorted_d)
#print(sorted_d)
#将字典挨个取出来
for i in range(len(sorted_d)-1):
res.append(sorted_d[i][0])
res.append(sorted_d[i][1])
#res.append(sorted_d[i])
#不能这样res.append(sorted_d[i][0][1])
return res
if __name__ == '__main__':
generator = ["yes","long","code","yes",
"code","baby","chrome",
"body","long","code"]
s = Solution()
print("输入:",generator)
#print("输入:","k =",k)
print(s.topKFrequentWords(generator))
#print("输出:",s.topKFrequentWords(generator,k))
也可以把它进行这样的改造,结合自己的错题本
让出错频率高的多出现几次
class Solution:
def topKFrequentWords(self,words):
dict = {}
res = []
for word in words:
if word not in dict:
dict[word] = 1
else:
dict[word] += 1
#这里是将字典进行排序
#这样就是从大到小的排序
#sorted_d = sorted(dict.items(),key=lambda x:x[1],reverse=True)
#这样就是从小到大的排序
sorted_d = sorted(dict.items(), key=lambda x: x[1])
print(sorted_d)
#print(sorted_d)
#将字典挨个取出来
for i in range(len(sorted_d)):
if int(sorted_d[i][1]) > 2:
res.append(sorted_d[i][0])
#res.append(sorted_d[i][1])
#res.append(sorted_d[i])
#不能这样res.append(sorted_d[i][0][1])
return res
if __name__ == '__main__':
import random
generator = ["yes","long","code","yes",
"code","baby","chrome",
"body","long","code","long","long","body","body"]
s = Solution()
print("输入:",generator)
#print("输入:","k =",k)
k = s.topKFrequentWords(generator)
while True:
k1 = random.randint(0, len(k) - 1)
z = input()
if z == '1':
print(k[k1])
else:
break