首頁  >  文章  >  後端開發  >  Python 統計字數的思路詳解

Python 統計字數的思路詳解

不言
不言原創
2018-05-08 16:18:492848瀏覽

這篇文章主要介紹了Python 統計字數的思路詳解,文中也給大家提供了不借助第三方模組的解決方法,有興趣的朋友一起看看吧

 問題描述:

用Python 實作函數count_words(),該函數輸入字串s 和數字n,傳回s 中n 個出現頻率最高的單字。傳回值是元組列表,包含出現次數最高的n 個字及其次數,即[(7d13091282e20cd2a8b7307a59e596b9, 412ce764aedc307ab82ffc52b2c4dcd0), (b363e2e08607babbe5f7b50fb07317bd, a210cef4ebc876fdda84a9e2005afc2d), ... ],依出現次數降序排列。

您可以假設所有輸入都是小寫形式,且不含標點符號或其他字元(只包含字母和單個空格)。若出現次數相同,則依字母順序排列。

例如:

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

from collections import defaultdict
"""Count words."""
def count_words(s, n):
  """Return the n most frequently occuring words in s."""
  split_s = s.split()
  map_list = [(k,1) for k in split_s]
  output = defaultdict(int)
  for d in map_list:
    output[d[0]] += d[1]
  output1 = dict(output)
  top_n = sorted(output1.items(), key=lambda pair:pair[0], reverse=False)
  top_n = sorted(top_n, key=lambda pair:pair[1], reverse=True)
  return top_n[: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", 4))
if __name__ == '__main__':
  test_run()

解決方案2(使用Counter)

from collections import Counter
"""Count words."""
def count_words(s, n):
  """Return the n most frequently occuring words in s."""
  split_s = s.split()
  split_s = Counter(name for name in split_s)
  print(split_s)
  top_n = sorted(split_s.items(), key=lambda pair:pair[0], reverse=False)
  print(top_n)
  top_n = sorted(top_n, key=lambda pair:pair[1], reverse=True)
  print(top_n)
  return top_n[: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", 4))
if __name__ == '__main__':
  test_run()

相關推薦:

Python實現計算圓周率π的值到任意位元的方法範例

以上是Python 統計字數的思路詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn