使用Python 統(tǒng)計高頻字?jǐn)?shù)的方法
問題
(來自Udacity機器學(xué)習(xí)工程師納米學(xué)位預(yù)覽課程)
用 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ù)降序排列。
可以假設(shè)所有輸入都是小寫形式,并且不含標(biāo)點符號或其他字符(只包含字母和單個空格)。如果出現(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)計高頻字?jǐn)?shù)的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
Python中的 any() 函數(shù)和 all() 函數(shù)
python中os.path.join()函數(shù)實例用法
Python增量循環(huán)刪除MySQL表數(shù)據(jù)的方法
Gradio機器學(xué)習(xí)模型快速部署工具應(yīng)用分享
Python圖片視頻超分模型RealBasicVSR的使用教程

