国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python 統計字數的思路詳解

2020-02-23 00:03:10
字體:
來源:轉載
供稿:網友

 問題描述:

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

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()            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 安福县| 林甸县| 景东| 新乐市| 聊城市| 牟定县| 永和县| 思茅市| 贞丰县| 景洪市| 津市市| 彩票| 双鸭山市| 宣武区| 安远县| 天峻县| 榆社县| 商丘市| 淳化县| 贵定县| 大荔县| 博爱县| 安化县| 收藏| 都兰县| 洛阳市| 寿阳县| 东兰县| 昭平县| 新宾| 上蔡县| 井陉县| 喀喇沁旗| 丹江口市| 庆城县| 玉树县| 张家川| 资阳市| 巴南区| 西青区| 临高县|