Python for Everybody(chapter 9. dictionary, words.py)

Yili Shih
3 min readNov 11, 2021

本文記錄閱讀Python for everybody文章內的範例程式, 加註解與變化題

主功能: 讀某個 英文文章的 .txt 檔, 數一數 哪一個字 使用的次數最多
the most commonly used word and how many times the word is used.

answer: the word “to” was used sixteen times in the first three paragraphs of this chapter

子技巧:
執行時動態輸入檔案名稱 words.txt
使用open打開 .txt ; 逐line 讀成一個string
透過loop, 存成 dictionary, 為每個 獨立字 計數出現次數;
透過loop, 逐步找出最大計數者,擔任 biggest frequent word
如何排序 dictionary 生冪或降冪
嘗試其他更簡潔的dictionary 找極大值或排序做法

#先準備好 word.txt , 假設它長得這樣
‘’’
Writing programs or programming is a very creative
and rewarding activity You can write programs for
many reasons ranging from making your living to solving
a difficult data analysis problem to having fun to helping
someone else solve a problem This book assumes that
{\em everyone} needs to know how to program and that once
you know how to program, you will figure out what you want
to do with your newfound skills

We are surrounded in our daily lives with computers ranging
from laptops to cell phones We can think of these computers
as our personal assistants who can take care of many things
on our behalf The hardware in our current-day computers
is essentially built to continuously ask us the question
What would you like me to do next

Our computers are fast and have vasts amounts of memory and
could be very helpful to us if we only knew the language to
speak to explain to the computer what we would like it to
do next If we knew this language we could tell the
computer to do tasks on our behalf that were repetitive
Interestingly, the kinds of things computers can do best
are often the kinds of things that we humans find boring
and mind-numbing
the the the the the the the the the the
‘’’

故意在末尾加了一堆 the ,想要創造最大字數有兩名同燈同分

避免輸入找不到的錯誤檔名
宣告空的字典物件
將字典應用於計數器
for loop, 歷遍字典內的逐一key 不在乎key的字母順序, 列印出來看看字典內的結果
希望以key的字母順序,列印出字典內容
to 16
印出一對對的key value …….(‘Writing’, 1)
bigword= to bigcount= 16
bigcount= 16 bigword= [‘to’, ‘the’]
answer=False
answer=True
使用 if else
使用 get

Reference: Exploring Data Using Python 3, by Dr. Charles R. Severance

--

--