【Python進階】用 Python 統計字數


問題描述:

用 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM