問題描述:
用 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 統計字數的思路詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。