作業三
Jump to Section
說明:請統計文章中,不同字所出現的次數為何。
- ‘I don’t care’ 視為三個字,分別為I, don’t, care各一次。
- play和plays 視為兩種字,同時出現時,各算一次。
成品及時展示:
思路說明
使用Counter模組。讀取檔案內容後,用.split()將內容以空格分開為陣列,在from collections import Counter後使用Counter(arr)得到計數結果,最後轉成字串輸出。
主要程式
from collections import Counter
def read_data(path):
with open(path) as f:
data = f.read().rstrip()
return data
article = read_data('data/article2.txt')
print(Counter(article.split()))
加分題
article = read_data('data/bonus.txt')
l = article.split()
n = []
for i in range(len(l)-1):
n.append(l[i] + " " + l[i+1])
print(Counter(n))