jesusjsc

Python实现统计单词个数&&实现多级排序
# Python实现统计单词个数&&实现多级排序 ---------- ``` python """...
扫描右侧二维码阅读全文
03
2019/04

Python实现统计单词个数&&实现多级排序

Python实现统计单词个数&&实现多级排序


"""Count words."""

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

    >>> print count_words("betty bought a bit of butter but the butter was bitter",3)
    [('butter', 2), ('a', 1), ('betty', 1)]
    """

    # TODO: Count the number of occurences of each word in s
    list_s = s.split(' ')
    set_s = set(list_s)
    top_n = []
    for s in set_s:
        top_n.append((s, list_s.count(s)))

    # # TODO: Sort the occurences in descending order (alphabetically in case of ties)
    # def cmp_fun(a, b):
    #     if a[1] > b[1]:
    #         return -1
    #     elif a[1] == b[1]:
    #         if a[0] < b[0]:
    #             return -1
    #         elif a[0] == b[0]:
    #             return 0
    #         else:
    #             return 1
    #     else:
    #         return 1
    #
    # top_n = sorted(top_n, cmp_fun)

    # TODO: Sort the occurences in descending order (alphabetically in case of ties)
    top_n = sorted(top_n, key=lambda top_n: top_n[0], reverse=False)
    top_n = sorted(top_n, key=lambda top_n: top_n[1], reverse=True)

    # TODO: Return the top n words as a list of tuples (<word>, <count>)
    top_n = top_n[:n]
    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()

结果如下:

[('cat', 3), ('bat', 2), ('mat', 1)]
[('butter', 2), ('a', 1), ('betty', 1)]

数字以降序排列,单词以升序排列

Last modification:May 27th, 2019 at 05:22 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment