欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用Python 統(tǒng)計(jì)高頻字?jǐn)?shù)的方法

 更新時(shí)間:2019年01月31日 14:57:31   作者:Silent_Summer  
今天小編就為大家分享一篇使用Python 統(tǒng)計(jì)高頻字?jǐn)?shù)的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧

問題

(來自Udacity機(jī)器學(xué)習(xí)工程師納米學(xué)位預(yù)覽課程)

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

可以假設(shè)所有輸入都是小寫形式,并且不含標(biāo)點(diǎn)符號或其他字符(只包含字母和單個(gè)空格)。如果出現(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é)

主要兩個(gè)小技巧:

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

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

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

相關(guān)文章

最新評論