问题描述:
用 Python 实现函数
count_words()
,该函数输入字符串s
和数字n
,返回s
中n
个出现频率最高的单词。返回值是一个元组列表,包含出现次数最高的n
个单词及其次数,即[(<单词1>, <次数1>), (<单词2>, <次数2>), ... ]
,按出现次数降序排列。您可以假设所有输入都是小写形式,并且不含标点符号或其他字符(只包含字母和单个空格)。如果出现次数相同,则按字母顺序排列。
例如:
print count_words("betty bought a bit of butter but the butter was bitter",3)
输出:
[(‘butter‘, 2), (‘a‘, 1), (‘betty‘, 1)]
解决问题的思路:
1. 将字符串s进行空白符分割得到所有的单词列表split_s,如:[‘betty‘, ‘bought‘, ‘a‘, ‘bit‘, ‘of‘, ‘butter‘, ‘but‘, ‘the‘, ‘butter‘, ‘was‘, ‘bitter‘]
2. 建立maplist,将split_s转化为元素为元组的列表形式,如:[(‘betty‘, 1), (‘bought‘, 1), (‘a‘, 1), (‘bit‘, 1), (‘of‘, 1), (‘butter‘, 1), (‘but‘, 1), (‘the‘, 1), (‘butter‘, 1), (‘was‘, 1), (‘bitter‘, 1)]
3. 合并maplist中元素,元组的第一个索引值相同,则将其第二个索引值相加。
// 备注:准备采用defaultdict。得到的数据如下:{‘betty‘: 1, ‘bought‘: 1, ‘a‘: 1, ‘bit‘: 1, ‘of‘: 1, ‘butter‘: 2, ‘but‘: 1, ‘the‘: 1, ‘was‘: 1, ‘bitter‘: 1}
4. 进行排序,按照key进行字母排序,得到如下:[(‘a‘, 1), (‘betty‘, 1), (‘bit‘, 1), (‘bitter‘, 1), (‘bought‘, 1), (‘but‘, 1), (‘butter‘, 2), (‘of‘, 1), (‘the‘, 1), (‘was‘, 1)]
5. 进行二次排序, 按照value进行排序,得到如下:[(‘butter‘, 2), (‘a‘, 1), (‘betty‘, 1), (‘bit‘, 1), (‘bitter‘, 1), (‘bought‘, 1), (‘but‘, 1), (‘of‘, 1), (‘the‘, 1), (‘was‘, 1)]
6. 使用切片取出频率较高的*组数据
总结:在python3上不进行defaultdict进行排序结果也是正确的,python2上不正确。defaultdict本身是没有顺序的,要区分列表,所以必须进行排序。
也可尝试自己写,不借助第三方模块
解决方案1(使用defaultdict):
1 from collections import defaultdict 2 """Count words.""" 3 4 def count_words(s, n): 5 """Return the n most frequently occuring words in s.""" 6 split_s = s.split() 7 map_list = [(k,1) for k in split_s] 8 output = defaultdict(int) 9 for d in map_list: 10 output[d[0]] += d[1] 11 output1 = dict(output) 12 top_n = sorted(output1.items(), key=lambda pair:pair[0], reverse=False) 13 top_n = sorted(top_n, key=lambda pair:pair[1], reverse=True) 14 15 return top_n[:n] 16 17 18 def test_run(): 19 """Test count_words() with some inputs.""" 20 print(count_words("cat bat mat cat bat cat", 3)) 21 print(count_words("betty bought a bit of butter but the butter was bitter", 4)) 22 23 24 if __name__ == ‘__main__‘: 25 test_run()
解决方案2(使用Counter)
1 from collections import Counter 2 """Count words.""" 3 4 def count_words(s, n): 5 """Return the n most frequently occuring words in s.""" 6 split_s = s.split() 7 split_s = Counter(name for name in split_s) 8 print(split_s) 9 top_n = sorted(split_s.items(), key=lambda pair:pair[0], reverse=False) 10 print(top_n) 11 top_n = sorted(top_n, key=lambda pair:pair[1], reverse=True) 12 print(top_n) 13 14 return top_n[:n] 15 16 17 def test_run(): 18 """Test count_words() with some inputs.""" 19 print(count_words("cat bat mat cat bat cat", 3)) 20 print(count_words("betty bought a bit of butter but the butter was bitter", 4)) 21 22 23 if __name__ == ‘__main__‘: 24 test_run() 25
原文地址:https://www.cnblogs.com/yongqiangyue/p/9006862.html