Python 統計字數的思路詳解
這篇文章主要介紹了Python 統計字數的思路詳解,文中也給大家提供了不借助第三方模組的解決方法,有興趣的朋友一起看看吧
問題描述:
用Python 實作函數count_words(),該函數輸入字串s 和數字n,傳回s 中n 個出現頻率最高的單字。傳回值是元組列表,包含出現次數最高的n 個字及其次數,即[(<單字1>, <次數1>), (<單字2>, <次數2>), ... ],依出現次數降序排列。
您可以假設所有輸入都是小寫形式,且不含標點符號或其他字元(只包含字母和單個空格)。若出現次數相同,則依字母順序排列。
例如:
print count_words("betty bought a bit of butter but the butter was bitter",3)
輸出:
[('butter', 2), ('a ', 1), ('betty', 1)]
解決問題的想法:
1. 將字串s進行空白符號分割得到所有的單字清單split_s,如:['betty', 'bought', 'a', 'bit', 'of', 'butter', 'but', 'the', 'butter' , 'was', 'bitter']
2. 建立maplist,將split_s轉換為元素為元組的列表形式,如:[('betty', 1), ('bought', 1) , ('a', 1), ('bit', 1), ('of', 1), ('butter', 1), ('but', 1), ('the', 1), ( 'butter', 1), ('was', 1), ('bitter', 1)]
#3. 合併maplist中元素,元組的第一個索引值相同,則將其第二個索引值相加。
// 備註:準備採用defaultdict。得到的資料如下:{'betty': 1, 'bought': 1, 'a': 1, 'bit': 1, 'of': 1, 'butter': 2, 'but': 1, 'the ': 1, 'was': 1, 'bitter': 1}
4. 進行排序,依照key進行字母排序,得到如下:[('a', 1), ('betty', 1), ('bit', 1), ('bitter', 1), ('bought', 1), ('but', 1), ('butter', 2), ('of', 1) , ('the', 1), ('was', 1)]
5. 進行二次排序, 依照value進行排序,得到如下:[('butter', 2), ('a ', 1), ('betty', 1), ('bit', 1), ('bitter', 1), ('bought', 1), ('but', 1), ('of', 1), ('the', 1), ('was', 1)]
6. 使用切片取出頻率較高的*組資料
總結:在python3上不進行defaultdict進行排序結果也是正確的,python2上不正確。 defaultdict本身是沒有順序的,要區分列表,所以必須進行排序。
也可嘗試自己寫,不借助第三方模組
解決方案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()
相關推薦:
以上是Python 統計字數的思路詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

在 Sublime Text 中運行 Python 代碼,需先安裝 Python 插件,再創建 .py 文件並編寫代碼,最後按 Ctrl B 運行代碼,輸出會在控制台中顯示。

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

Golang在性能和可擴展性方面優於Python。 1)Golang的編譯型特性和高效並發模型使其在高並發場景下表現出色。 2)Python作為解釋型語言,執行速度較慢,但通過工具如Cython可優化性能。

在 Visual Studio Code(VSCode)中編寫代碼簡單易行,只需安裝 VSCode、創建項目、選擇語言、創建文件、編寫代碼、保存並運行即可。 VSCode 的優點包括跨平台、免費開源、強大功能、擴展豐富,以及輕量快速。

在 Notepad 中運行 Python 代碼需要安裝 Python 可執行文件和 NppExec 插件。安裝 Python 並為其添加 PATH 後,在 NppExec 插件中配置命令為“python”、參數為“{CURRENT_DIRECTORY}{FILE_NAME}”,即可在 Notepad 中通過快捷鍵“F6”運行 Python 代碼。
