-----------------------------------------
圖片放大特效
table樣式

<style scoped>
img[alt="Alt1"]{
background: rgba(255, 255, 255, 0);
position: absolute;
top: 10%;
left: 10%;
/* transform: translate(-50%, -50%); */
width: 200px; /* 調整圖片寬度 */
height: auto; /* 保持原始比例 */
padding:0;
margin:0;
z-index: 1;
}
img[alt="Alt2"]{
background: rgba(255, 255, 255, 0);
position: absolute;
top: 10%;
left: 75%;
/* transform: translate(-50%, -50%); */
width: 200px; /* 調整圖片寬度 */
height: auto; /* 保持原始比例 */
padding:0;
margin:0;
z-index: 2;
}
</style>
- [學習目標](#學習目標)
- [日記系統實作](#日記系統實作)
- [運算思維總整理](#運算思維總整理)
- [本週總結](#本週總結)
---
# 小練習 2

---
## 🎮 小練習 2:完整日記系統
### 任務說明
擴充我們的日記系統,增加以下功能:
---
**練習 2-1**:統計功能
- 顯示日記總數
- 顯示總字數
- 找出最長的日記
```python
# filepath: practice2_1.py
def diary_statistics():
"""顯示日記統計資訊"""
# 請完成這個函式
pass
```
---
**練習 2-2**:分類功能
- 為日記加上心情標籤(開心、難過、平淡)
- 可以按心情搜尋日記
```python
# filepath: practice2_2.py
def write_diary_with_mood():
"""寫日記時加上心情標籤"""
# 提示:在日記中加入「心情:開心」這樣的標記
pass
def search_by_mood(mood):
"""依心情搜尋日記"""
pass
```
---
**練習 2-3**:匯出功能
- 將日記匯出為 HTML 格式
- 可以用瀏覽器開啟查看
```python
# filepath: practice2_3.py
def export_to_html():
"""將日記匯出為 HTML 檔案"""
# 提示:HTML 基本結構
# <html><body><h1>標題</h1><p>內容</p></body></html>
pass
```
---
### ✅ 參考解答
```python
# filepath: practice2_solution.py
def diary_statistics():
"""顯示日記統計資訊"""
try:
with open('my_diary.txt', 'r', encoding='utf-8') as file:
content = file.read()
entries = content.split('=' * 40)
# 過濾空白項目
entries = [e for e in entries if e.strip()]
total_entries = len(entries) // 2 # 每篇日記有兩條分隔線
total_chars = len(content)
print(f'📊 日記統計')
print(f'總篇數:{total_entries} 篇')
print(f'總字數:{total_chars} 字')
except FileNotFoundError:
print('還沒有日記!')
```
---
```python
# filepath: practice2_solution.py
def write_diary_with_mood():
"""寫日記時加上心情標籤"""
print('\n=== 寫日記 ===')
print('選擇今天的心情:')
print('1. 😊 開心')
print('2. 😢 難過')
print('3. 😐 平淡')
mood_choice = input('請選擇 (1-3):')
moods = {'1': '開心😊', '2': '難過😢', '3': '平淡😐'}
mood = moods.get(mood_choice, '平淡😐')
content = input('請輸入今天的日記內容:')
now = datetime.now()
date_str = now.strftime('%Y-%m-%d %H:%M:%S')
```
---
```python
# filepath: practice2_solution.py
with open('my_diary.txt', 'a', encoding='utf-8') as file:
file.write('=' * 40 + '\n')
file.write(f'日期:{date_str}\n')
file.write(f'心情:{mood}\n')
file.write('=' * 40 + '\n')
file.write(f'{content}\n\n')
print('✅ 日記已保存!')
def search_by_mood(mood):
"""依心情搜尋日記"""
mood_map = {'1': '開心😊', '2': '難過😢', '3': '平淡😐'}
search_mood = mood_map.get(mood)
```
---
```python
# filepath: practice2_solution.py
try:
with open('my_diary.txt', 'r', encoding='utf-8') as file:
content = file.read()
entries = content.split('=' * 40)
found = False
for i in range(0, len(entries), 2):
if i+1 < len(entries):
entry = entries[i] + '=' * 40 + entries[i+1]
if f'心情:{search_mood}' in entry:
print(entry)
found = True
if not found:
print(f'沒有找到心情為「{search_mood}」的日記')
except FileNotFoundError:
print('還沒有日記!')
```
---
```python
# filepath: practice2_solution.py
def export_to_html():
"""將日記匯出為 HTML 檔案"""
try:
with open('my_diary.txt', 'r', encoding='utf-8') as file:
content = file.read()
html = f'''
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>我的日記本</title>
<style>
body {{ font-family: Arial, sans-serif; margin: 20px; }}
h1 {{ color: #2c3e50; }}
.entry {{ border: 2px solid #3498db; padding: 15px;
margin: 20px 0; background-color: #ecf0f1; }}
</style>
</head>
<body>
<h1>📔 我的日記本</h1>
<pre class="entry">{content}</pre>
</body>
</html>
'''
```
---
```python
# filepath: practice2_solution.py
with open('my_diary.html', 'w', encoding='utf-8') as file:
file.write(html)
print('✅ 日記已匯出為 my_diary.html')
print('可以用瀏覽器開啟查看!')
except FileNotFoundError:
print('還沒有日記!')
```
---
```python
# filepath: example_code.py
def safe_file_operation(filename, mode, operation):
"""安全的檔案操作演算法"""
try:
# 步驟1: 開啟檔案
with open(filename, mode, encoding='utf-8') as file:
# 步驟2: 執行操作
result = operation(file)
# 步驟3: 自動關閉(with語法)
return result
except FileNotFoundError:
print(f'錯誤:檔案 {filename} 不存在')
return None
except Exception as e:
print(f'發生錯誤:{e}')
return None
# 使用範例
def read_operation(file):
return file.read()
content = safe_file_operation('data.txt', 'r', read_operation)
```
---
```python
# filepath: example_code.py
# 問題分解範例:將大問題分成小函式
# 小問題1:格式化日期
def format_date():
from datetime import datetime
return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 小問題2:格式化日記項目
def format_entry(date, content):
return f'=' * 40 + f'\n日期:{date}\n' + '=' * 40 + f'\n{content}\n\n'
# 小問題3:寫入檔案
def append_to_file(filename, content):
with open(filename, 'a', encoding='utf-8') as file:
file.write(content)
```
---
```python
# filepath: example_code.py
# 組合小問題解決大問題
def write_diary_entry(content):
"""組合所有小函式完成寫日記功能"""
date = format_date()
entry = format_entry(date, content)
append_to_file('diary.txt', entry)
print('✅ 日記已保存!')
# 使用
write_diary_entry('今天學會了問題分解!')
```
---
### 🎯 運算思維實踐
**在日記系統中的應用**
| 運算思維 | 在日記系統中的體現 |
|----------|-------------------|
| 抽象化 | 將檔案視為資料容器,不關心底層實作 |
| 演算法思維 | 設計安全的檔案操作流程 |
| 問題分解 | 將系統分成寫入、讀取、搜尋等模組 |
| 模式識別 | 識別日記的共同格式(日期+內容) |
---
#### 作業 1-2:單字本系統 (30%)
製作一個英文單字本,可以記錄單字和中文意思:
```python
# filepath: homework1_2.py
# 1. 新增單字:輸入英文單字和中文意思
# 2. 查看所有單字
# 3. 隨機測驗:隨機顯示一個單字,請使用者輸入中文
# 4. 統計單字數量
# 檔案格式範例 (words.txt)
# apple=蘋果
# banana=香蕉
# computer=電腦
```
---
#### 作業 1-3:檔案讀寫測驗 (30%)
回答以下問題並寫出程式碼:
```python
# filepath: homework1_3.py
# 問題1:為什麼要使用 with 語法?(10%)
# 回答:
# 問題2:寫出一個程式,讀取 data.txt 並:(20%)
# - 計算檔案有幾行
# - 計算檔案有幾個字
# - 找出最長的一行
```
---
#### 作業 2-2:學生成績管理系統 (50%)
製作一個成績管理系統:
```python
# filepath: homework2_2.py
# 必要功能:
# 1. 新增學生成績(姓名、科目、分數)
# 2. 查詢某位學生的所有成績
# 3. 計算某位學生的平均分數
# 4. 找出某科目的最高分和最低分
# 5. 產生成績報表(存成 report.txt)
# 提示:可以使用 CSV 格式
# 姓名,科目,分數
# 小明,數學,95
# 小明,英文,87
```
**評分標準**:
- 創意性 (30%)
- 功能完整性 (30%)
- 程式品質 (20%)
- 使用者體驗 (20%)
---
### 📤 繳交規定
1. **檔案命名**:`學號_姓名_week12.py`
2. **程式碼要求**:
- 每個函式都要有註解說明
- 變數命名要有意義
- 適當的錯誤處理
3. **測試資料**:
- 附上測試用的資料檔案
- 或在程式中說明如何建立測試資料
---
4. **執行結果**:
- 擷取程式執行的畫面
- 展示各個功能的運作
5. **繳交期限**:下週上課前
**加分項目**:
- 程式有完善的使用說明
- 有創意的功能設計
- 優秀的使用者介面
---
### 🎓 學習資源
**推薦閱讀**:
- Python 官方文件:檔案 I/O
- 《Python 程式設計入門》第 8 章
- 線上教學影片:檔案處理基礎
**練習平台**:
- LeetCode:檔案相關題目
- HackerRank:File Handling 專區
---
下週預告:
## Week 13: 檔案處理(下) - 進階技巧與應用
- JSON 檔案處理
- CSV 檔案處理
- 檔案與資料夾操作
- 實作通訊錄系統
期待與你們一起繼續學習!🚀
---
# 謝謝大家!👏
### 有問題隨時發問!
### 記得完成作業喔!📝