python英文高频句统计_使用Python 统计高频字数的方法
問題
(來自Udacity機器學習工程師納米學位預覽課程)
用 Python 實現函數 count_words(),該函數輸入字符串 s 和數字 n,返回 s 中 n 個出現頻率最高的單詞。返回值是一個元組列表,包含出現次數最高的 n 個單詞及其次數,即 [(, ), (, ), ... ],按出現次數降序排列。
可以假設所有輸入都是小寫形式,并且不含標點符號或其他字符(只包含字母和單個空格)。如果出現次數相同,則按字母順序排列。
例如:
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()
小結
主要兩個小技巧:
用split()將輸入字符串按空格分開;
用sorted()函數對字典 先按值,再按鍵 進行排序,尤其是item:(-item[1], item[0])) 代表先對item的第二個元素 降序 排列(item 之前用了-),然后對第一個元素 升序 排列。多個元素的元組亦然。
以上這篇使用Python 統計高頻字數的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持dt貓。
總結
以上是生活随笔為你收集整理的python英文高频句统计_使用Python 统计高频字数的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python基础函数图_Python基础
- 下一篇: 我国战车部队起源