Python 統(tǒng)計(jì)字?jǐn)?shù)的思路詳解
問題描述:
用 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)符號(hào)或其他字符(只包含字母和單個(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)]
解決問題的思路:
1. 將字符串s進(jìn)行空白符分割得到所有的單詞列表split_s,如:['betty', 'bought', 'a', 'bit', 'of', 'butter', 'but', 'the', 'butter', 'was', 'bitter']
2. 建立maplist,將split_s轉(zhuǎn)化為元素為元組的列表形式,如:[('betty', 1), ('bought', 1), ('a', 1), ('bit', 1), ('of', 1), ('butter', 1), ('but', 1), ('the', 1), ('butter', 1), ('was', 1), ('bitter', 1)]
3. 合并maplist中元素,元組的第一個(gè)索引值相同,則將其第二個(gè)索引值相加。
// 備注:準(zhǔn)備采用defaultdict。得到的數(shù)據(jù)如下:{'betty': 1, 'bought': 1, 'a': 1, 'bit': 1, 'of': 1, 'butter': 2, 'but': 1, 'the': 1, 'was': 1, 'bitter': 1}
4. 進(jìn)行排序,按照key進(jìn)行字母排序,得到如下:[('a', 1), ('betty', 1), ('bit', 1), ('bitter', 1), ('bought', 1), ('but', 1), ('butter', 2), ('of', 1), ('the', 1), ('was', 1)]
5. 進(jìn)行二次排序, 按照value進(jìn)行排序,得到如下:[('butter', 2), ('a', 1), ('betty', 1), ('bit', 1), ('bitter', 1), ('bought', 1), ('but', 1), ('of', 1), ('the', 1), ('was', 1)]
6. 使用切片取出頻率較高的*組數(shù)據(jù)
總結(jié):在python3上不進(jìn)行defaultdict進(jìn)行排序結(jié)果也是正確的,python2上不正確。defaultdict本身是沒有順序的,要區(qū)分列表,所以必須進(jìn)行排序。
也可嘗試自己寫,不借助第三方模塊
解決方案1(使用defaultdict):
from collections import defaultdict
"""Count words."""
def count_words(s, n):
"""Return the n most frequently occuring words in s."""
split_s = s.split()
map_list = [(k,1) for k in split_s]
output = defaultdict(int)
for d in map_list:
output[d[0]] += d[1]
output1 = dict(output)
top_n = sorted(output1.items(), key=lambda pair:pair[0], reverse=False)
top_n = sorted(top_n, key=lambda pair:pair[1], reverse=True)
return top_n[: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", 4))
if __name__ == '__main__':
test_run()
解決方案2(使用Counter)
from collections import Counter
"""Count words."""
def count_words(s, n):
"""Return the n most frequently occuring words in s."""
split_s = s.split()
split_s = Counter(name for name in split_s)
print(split_s)
top_n = sorted(split_s.items(), key=lambda pair:pair[0], reverse=False)
print(top_n)
top_n = sorted(top_n, key=lambda pair:pair[1], reverse=True)
print(top_n)
return top_n[: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", 4))
if __name__ == '__main__':
test_run()
總結(jié)
以上所述是小編給大家介紹的Python 統(tǒng)計(jì)字?jǐn)?shù)的思路詳解,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
淺談?dòng)肞ython實(shí)現(xiàn)一個(gè)大數(shù)據(jù)搜索引擎
這篇文章主要介紹了淺談?dòng)肞ython實(shí)現(xiàn)一個(gè)大數(shù)據(jù)搜索引擎,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-11-11
tensorflow 獲取模型所有參數(shù)總和數(shù)量的方法
今天小編就為大家分享一篇tensorflow 獲取模型所有參數(shù)總和數(shù)量的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06
Python編程基礎(chǔ)之構(gòu)造方法和析構(gòu)方法詳解
這篇文章主要為大家詳細(xì)介紹了Python的構(gòu)造方法和析構(gòu)方法,使用Python編程基礎(chǔ),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01
python實(shí)現(xiàn)Adapter模式實(shí)例代碼
這篇文章主要介紹了python實(shí)現(xiàn)Adapter模式實(shí)例代碼,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02
Pandas創(chuàng)建DataFrame提示:type?object?'object'?has?n
Pandas數(shù)據(jù)幀(DataFrame)是二維數(shù)據(jù)結(jié)構(gòu),它包含一組有序的列,每列可以是不同的數(shù)據(jù)類型,這篇文章主要給大家介紹了關(guān)于Pandas創(chuàng)建DataFrame提示:type?object?‘object‘?has?no?attribute?‘dtype‘的解決方案,需要的朋友可以參考下2023-02-02

