python笑傲江湖统计字数_Udacity.深度学习.用 Python 统计字数.2017-10-30

问题

用 Python 实现函数 count_words(),该函数输入字符串 s 和数字 n,返回 s 中 n 个出现频率最高的单词。返回值是一个元组列表,包含出现次数最高的 n 个单词及其次数,即 [(, ), (, ), ... ],按出现次数降序排列。

可以假设所有输入都是小写形式,并且不含标点符号或其他字符(只包含字母和单个空格)。如果出现次数相同,则按字母顺序排列。

例如:

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()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值