計算每個字詞出現的次數,區分大小寫(Python Dict 預設就是大小寫敏感)
這題開始有一點點難度了
輸入
We tried list and we tried dicts also we tried Zen
輸出
and 1
We 1
tried 3
dicts 1
list 1
we 2
also 1
Zen 1
首先將輸入字串,按照空白字元做切割,得到一個陣列
['We', 'tried', 'list', 'and', 'we', 'tried', 'dicts', 'also', 'we', 'tried', 'Zen']
用迴圈迭代跑過一輪
當字典裡有目前的字(key),數字(value)就+1。
若字典裡還沒有,則創造此字(key),數字(value)為1。
程式碼:
s = "We tried list and we tried dicts also we tried Zen"
counts = dict()
for word in s.split():
counts[word] = counts.get(word, 0) + 1
for key,value in counts.items():
print(key, value)
注意最後印出不能直接print(d)
而是要按照插入字典時的順序(所以題目的Hint中有這一段d.items()
)
或者使用 defaultdict
from collections import defaultdict
def count_word_occurrences(s):
counts = defaultdict(int) # 使用defaultdict來將value初始化為0
for word in s.split():
counts[word] += 1
for word, count in counts.items():
print(word, count)
s = "We tried list and we tried dicts also we tried Zen"
count_word_occurrences(s)