【Python進階】用 Python 統計字數

來源:互聯網
上載者:User

標籤:圖片   alt   輸入   was   建立   ict   word   some   main   

問題描述:

用 Python 實現函數 count_words(),該函數輸入字串 s 和數字 n,返回 sn 個出現頻率最高的單詞。傳回值是一個元組列表,包含出現次數最高的 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()
View Code

解決方案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 
View Code

【Python進階】用 Python 統計字數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.