python简单应用:字数统计

每次写代码,LZ感觉还是得自己手敲一遍。。。一遍?一遍哪够?看着别人现成的代码觉得自己都能看的懂,等到自己上手解决自己任务的时候,才发现根本不是这么一回事。看了很多大神的博客,基本上都有一颗强大的内心,为啥?码了那么久的代码,结果一个bug就可能前功尽弃,从头再来,也是只能默默鼓励下自己:每天进步一点点!

"""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 re
    listOfTokens = re.split(r'\W*', s)
    # print (listOfTokens)
    ss = set(listOfTokens)
    # print (ss)
    bow = [0] * len(ss)
    ll = list(ss)
    for word in listOfTokens:
        if word in ss:
            bow[ll.index(word)] += 1

    dd = {}

    for i in range(len(ss)):
        dd[ll[i]] = bow[i]

    # sort_dd = sorted(dd.items(), key = lambda asd:asd[1], reverse = True)
    sort_dd = sorted(dd.items(), key = lambda asd:(-asd[1], asd[0]))
    top_ll = dict(sort_dd[0:n])
    top_n = top_ll.keys()
    # 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()

test_run()

代码量不大,但是对于python入门的新手任务来说还是有挑战的O(∩_∩)O

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值