溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用Python 統(tǒng)計高頻字數(shù)的方法

發(fā)布時間:2020-09-17 00:52:12 來源:腳本之家 閱讀:221 作者:Silent_Summer 欄目:開發(fā)技術(shù)

問題

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

用 Python 實現(xiàn)函數(shù) count_words(),該函數(shù)輸入字符串 s 和數(shù)字 n,返回 s 中 n 個出現(xiàn)頻率最高的單詞。返回值是一個元組列表,包含出現(xiàn)次數(shù)最高的 n 個單詞及其次數(shù),即 [(<單詞1>, <次數(shù)1>), (<單詞2>, <次數(shù)2>), ... ],按出現(xiàn)次數(shù)降序排列。

可以假設所有輸入都是小寫形式,并且不含標點符號或其他字符(只包含字母和單個空格)。如果出現(xiàn)次數(shù)相同,則按字母順序排列。

例如:

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_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", 3)


if __name__ == '__main__':
  test_run()

小結(jié)

主要兩個小技巧:

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

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

以上這篇使用Python 統(tǒng)計高頻字數(shù)的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI