Udacity.深度学习.用 Python 统计字数.2017-10-30

用 Python 统计高频字数
python排序问题
Python标准库——collections模块的Counter类

问题
用 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)]
"""Count words."""

def count_words(s, n):
    """Return the n most frequently occuring words in s."""

    # TODO: Count the number of occurences of each word in s
    import collections
    top = collections.Counter(s.split()).most_common()
    # print(collections.Counter(s.split()).most_common())

    # TODO: Sort the occurences in descending order (alphabetically in case of ties)
    top.sort(key=lambda t:(-t[1], t[0]))
    top_n = top[:n]
    
    # TODO: Return the top n most frequent words.
    return top_n


def test_run():
    """Test count_words() with some inputs."""
    print count_words("cat bat mat cat bat cat", 3)
    print count_words("betty bought a bit of butter but the butter was bitter", 3)


if __name__ == '__main__':
    test_run()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 计算机二级C语言上机题库(南开版) 1.m个人的成绩存放在score数组中,请编写函数fun,它的功能是:将低于平...
    MrSunbeam阅读 11,542评论 1 42
  • python学习笔记 声明:学习笔记主要是根据廖雪峰官方网站python学习学习的,另外根据自己平时的积累进行修正...
    renyangfar阅读 8,266评论 0 10
  • 最近在慕课网学习廖雪峰老师的Python进阶课程,做笔记总结一下重点。 基本变量及其类型 变量 在Python中,...
    victorsungo阅读 5,779评论 0 5
  • 一、python 变量和数据类型 1.整数 Python可以处理任意大小的整数,当然包括负整数,在Python程序...
    绩重KF阅读 5,869评论 0 1
  • 你可以拥有全世界 可是它的世界只有你 永远记得 第一次抱着它进家门的时候 它既害怕 又好奇 跟着我屁股后面转啊转啊...
    其實生活沒道里阅读 2,498评论 0 0

友情链接更多精彩内容