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

首頁 > 編程 > Python > 正文

使用Python 統計高頻字數的方法

2020-02-16 01:01:22
字體:
來源:轉載
供稿:網友

問題

(來自Udacity機器學習工程師納米學位預覽課程)

用 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)]

解法

"""Count words."""def count_words(s, n):  """Return the n most frequently occuring words in s."""  w = {}  sp = s.split()  # TODO: Count the number of occurences of each word in s  for i in sp:    if i not in w:      w[i] = 1    else:      w[i] += 1  # TODO: Sort the occurences in descending order (alphabetically in case of ties)  top = sorted(w.items(), key=lambda item:(-item[1], item[0]))  top_n = top[:n]  # TODO: Return the top n most frequent words.  return top_ndef 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()

小結

主要兩個小技巧:

用split()將輸入字符串按空格分開;

用sorted()函數對字典 先按值,再按鍵 進行排序,尤其是item:(-item[1], item[0])) 代表先對item的第二個元素 降序 排列(item 之前用了-),然后對第一個元素 升序 排列。多個元素的元組亦然。

以上這篇使用Python 統計高頻字數的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 灵石县| 通辽市| 商水县| 中江县| 枣庄市| 伊吾县| 宁海县| 永寿县| 东乌| 丹东市| 南乐县| 商水县| 喜德县| 夹江县| 昌乐县| 金寨县| 文水县| 芷江| 枣阳市| 曲周县| 驻马店市| 玉田县| 京山县| 靖江市| 双桥区| 陵川县| 衡东县| 阳江市| 崇信县| 汪清县| 蕲春县| 城市| 西城区| 泽普县| 固阳县| 凤山市| 蕉岭县| 万宁市| 天津市| 许昌市| 牙克石市|