# Python - 輕鬆學會寫程式
###### tags: `YOTTA` `PYTHON`
## 17. 資料型別(Data Types)
data types (種類)
資料型別
1. 整數 integer int
2. 浮點數 float
3. 布林值 boolean bool (True, False)
4. 字串 string str 'Tim'
## 19. 第一次上傳到GitHub
```python=
git init //初始化
git add README.md //加入追蹤清單
git commit -m "first commit" //建立版本
git push -u origin master //上傳
```
#### 上傳GitHub三寶
```python=
git add 檔案名稱 //加入追蹤清單
git commit -m "版本訊息" //建立版本
git push origin master //上傳
```
## 24. 比較符號 (Comparison Operators)
```python=
x = 5
print(x == 5) # True
print(x != 5) # False
print(x > 2) # True
print(x < 2) # False
print(x >= 2) # True
print(x <= 2) # False
```
## 27. 型別轉換 (Casting)
```python=
age = int(age) # 型別轉換為整數
```
## 33. While True (無限迴圈)
```python=
while True:
print('x小於10喔!')
print('我還困在裡面')
break # 逃出迴圈
print('我逃出迴圈了!')
```
```python=
while True:
mode = input('請輸入遊戲模式: ')
if mode == 'q': # quit
break
elif mode == '1':
print('啟動模式一')
elif mode == '2':
print('啟動模式二')
else:
print('你只能輸入1/2/q')
```
## 35. [程式練習] 密碼重試程式
```python=
# 密碼重試程式
# password = 'a123456'
# 讓使用者重複輸入密碼
# 最多輸入3次
# 如果正確就印出"登入成功!"
# 如果不正確就印出"密碼錯誤! 還有_次機會!"
#第一次自己打
chance = 3
while chance > 0:
password_input = input('請輸入密碼: ')
password = 'a123456'
chance = chance - 1
if password_input == password:
print('登入成功!')
break
elif chance > 0:
print('密碼錯誤! 還有', chance, '次機會')
else:
print('登入失敗')
# 解答
# password = 'a123456'
# i = 3 # 剩餘機會
# while True:
# pwd = input('請輸入密碼: ')
# if pwd == password:
# print('登入成功!')
# break # 逃出迴圈
# else:
# i = i - 1
# print('密碼錯誤! 還有', i, '次機會')
# if i == 0:
# print('登入失敗')
# break
```
## 39. List 清單
```python=
# list 清單
a = ['Toyota', 'Honda'] # 空清單
print(a)
print(a[0])
print(a[1])
a.append('Audi') # 加東西
print(a)
print(a[0], a[1], a[2])
print(len(a)) # 取長度
print('Audi' in a) # 是非題 True, False
print('Benze' in a)
```
## 42. 讀取檔案
read : r
write : w
as : 當作
```python=
data = []
with open('food.txt', 'r') as f: # with:自動close ; [檔案]當作f
for line in f:
data.append(line.strip()) #strip()除掉換行符號
print(data)
```
## 45. 清單的篩選
for loop的意思就是:把清單中的東西一個一個拿出來
## 48. Range 延伸
```python=
range(2, 5) # [2, 3, 4] 結束值不包含
range(8, 10) # [8, 9]
range(2, 10, 3) # [2, 5, 8] range(開始,結束,遞增)
```
## 52. 寫入欄位名稱 + 編碼問題
```python=
products = [] # 大清單
while True:
name = input('請輸入商品名稱: ')
if name == 'q': # quit
break
price = input('請輸入商品價格: ')
price = int(price)
# p = [] # 小清單
# p.append(name)
# p.append(price)
# p = [name, price]
# products.append(p) # 把小清單塞進大清單
products.append([name, price]) # 最簡潔寫法
print(products)
for p in products:
print(p[0], '的價格是', p[1])
with open('products.csv', 'w', encoding = 'utf-8') as f:
f.write('商品, 價格\n')
for p in products:
f.write(p[0] + ',' + str(p[1]) + '\n')
```
## 49. 建立記帳程式專案 (+二維清單)
```python=
import os # operating system
products = [] # 大清單
if os.path.isfile('products.csv'): # 檢查檔案在不在
print('yeah! 找到檔案了!')
# 如果有products.csv這個檔案,就讀取
with open('products.csv', 'r', encoding = 'utf-8') as f:
for line in f:
if '商品,價格' in line:
continue # 放棄這回,跳到下一回開始
name, price = line.strip().split(',') #每一行用什麼東西切割
# s = line.strip().split(',')
# name = s[0]
# price = s[1]
products.append([name, price])
print(products)
else:
print('找不到檔案...')
# 讓使用者輸入
while True:
name = input('請輸入商品名稱: ')
if name == 'q': # quit
break
price = input('請輸入商品價格: ')
price = int(price)
# p = [] # 小清單
# p.append(name)
# p.append(price)
# p = [name, price]
# products.append(p) # 把小清單塞進大清單
products.append([name, price]) # 最簡潔寫法
print(products)
# 印出所有購買紀錄
for p in products:
print(p[0], '的價格是', p[1])
# 寫入檔案
with open('products.csv', 'w', encoding = 'utf-8') as f:
f.write('商品,價格\n')
for p in products:
f.write(p[0] + ',' + str(p[1]) + '\n')
```
## 60. Refactor (程式重構) part 2
### Function的中心思想是"只做一件事"
```python=
import os # operating system
# 讀取檔案
def read_file(fileName):
products = [] # 大清單
# 如果有products.csv這個檔案,就讀取
with open(fileName, 'r', encoding = 'utf-8') as f:
for line in f:
if '商品,價格' in line:
continue # 放棄這回,跳到下一回開始
name, price = line.strip().split(',') #每一行用什麼東西切割
# s = line.strip().split(',')
# name = s[0]
# price = s[1]
products.append([name, price])
return products
# 讓使用者輸入
def user_input(products):
while True:
name = input('請輸入商品名稱: ')
if name == 'q': # quit
break
price = input('請輸入商品價格: ')
price = int(price)
# p = [] # 小清單
# p.append(name)
# p.append(price)
# p = [name, price]
# products.append(p) # 把小清單塞進大清單
products.append([name, price]) # 最簡潔寫法
print(products)
return products
# 印出所有購買紀錄
def print_products(products):
for p in products:
print(p[0], '的價格是', p[1])
# 寫入檔案
def write_file(fileName, products):
with open(fileName, 'w', encoding = 'utf-8') as f:
f.write('商品,價格\n')
for p in products:
f.write(p[0] + ',' + str(p[1]) + '\n')
def main():
fileName = 'products.csv'
if os.path.isfile(fileName): # 檢查檔案在不在
print('yeah! 找到檔案了!')
products = read_file(fileName)
else:
print('找不到檔案...')
products = user_input(products)
print_products(products)
write_file('products.csv', products)
main()
```
## 61. [程式練習] 對話紀錄1 - 格式改寫
```python=
def read_file(fileName):
lines = []
with open(fileName, 'r', encoding='utf-8-sig')as f:
for line in f:
lines.append(line.strip())
return lines
def convert(lines):
new = []
person = None # 避開第一行line不是人名
for line in lines:
if line == 'Allen':
person = 'Allen'
continue
elif line == 'Tom':
person = 'Tom'
continue
if person: # 如果person有值
new.append(person + ': ' + line)
return new
def write_file(fileName, lines):
with open(fileName, 'w') as f:
for line in lines:
f.write(line + '\n')
def main():
lines = read_file('input.txt')
lines = convert(lines) # lines就是覆蓋再覆蓋
write_file('output.txt', lines)
main()
```
## 63. 清單的切割
### 清單的切割寫法:
n = [2, 6, 6, 8, 4]
* n[:3] 可以拿到前三個 (0可省略) # 2,6,6
* n[2:4] 可以拿到一個清單裝著 n[2] 跟 n[3] # 6,8
* n[-2:] 可以拿到最後兩個 # 8,4
## 64. [程式練習] 對話紀錄2 - part 2
```python=
# LINE對話紀錄裡講了幾個字、幾個圖片
def read_file(fileName):
lines = []
with open(fileName, 'r', encoding='utf-8-sig')as f:
for line in f:
lines.append(line.strip())
return lines
def convert(lines):
new = []
person = None # 避開第一行line不是人名
allen_word_count = 0
allen_sticker_count = 0
allen_img_count = 0
viki_word_count = 0
viki_sticker_count = 0
viki_img_count = 0
for line in lines:
s = line.split(' ') # 切割完會變清單
time = s[0]
name = s[1]
if name == 'Allen':
if s[2] == '貼圖':
allen_sticker_count += 1
elif s[2] == '圖片':
allen_img_count += 1
else:
for m in s[2:]:
allen_word_count += len(m)
elif name == 'Viki':
if s[2] == '貼圖':
viki_sticker_count += 1
elif s[2] == '圖片':
viki_img_count += 1
else:
for m in s[2:]:
viki_word_count += len(m)
print('allen說了', allen_word_count, '個字,傳了', allen_sticker_count, '個貼圖和', allen_img_count, '個圖片')
print('viki說了', viki_word_count, '個字,傳了', viki_sticker_count, '個貼圖和', viki_img_count, '個圖片')
# print(s)
return new
def write_file(fileName, lines):
with open(fileName, 'w') as f:
for line in lines:
f.write(line + '\n')
def main():
lines = read_file('LINE-Viki.txt')
lines = convert(lines) # lines就是覆蓋再覆蓋
# write_file('output.txt', lines)
main()
```
## 67. [程式練習] 一百萬筆留言中最常出現哪些字
```python=
data = []
count = 0
with open('reviews.txt', 'r') as f:
for line in f:
data.append(line)
count += 1 # count = count + 1
if count % 100000 == 0: # %求餘數
print(len(data))
print('檔案讀取完了, 總共有', len(data), '筆資料')
print(data[0])
#文字計數
word_count = {}
for d in data:
words = d.split() # split預設值是空白鍵
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
for word in word_count:
if word_count[word] > 1000000:
print(word, word_count[word])
# print(len(word_count))
# print(word_count['Allen'])
while True:
word = input('請問你想查什麼字: ')
if word == 'q':
break
if word in word_count:
print(word, '出現過的次數為: ',word_count[word])
else:
print('這個字沒有出現在留言中喔!')
print('感謝使用本查詢功能')
sum_len = 0
new = []
# good = []
for d in data:
sum_len += len(d) # sum_len = sum_len + len(d)
# print(sum_len)
if len(d) < 100: # 把長度低於100的留言裝至new清單
new.append(d)
# if 'good' in d:
# good.append(d)
print('留言的平均長度為', sum_len / len(data))
print('一共有', len(new), '筆留言長度小於100')
print(new[0])
print(new[1])
# print('一共有', len(good), '筆留言含有good')
good = [1 for d in data if 'good' in d]
print(good)
bad = ['bad' in d for d in data] # 運算
print(bad)
# bad = []
# for d in data:
# bad.append('bad' in d)
```
## 第三方套件
1. proressbar # 進度條
2. openpyxl # excel處理
3. python-docx # word處理
4. matplotlib # 圖表
5. twilio # 寄送簡訊
6. flask # 主流伺服器網頁(程式)
7. django # 主流大規模伺服器網頁(網頁)
#### 第三方套件位址
```
```
## 73. 處理 Excel 檔 (應用展示)
```python=
from openpyxl import Workbook
wb = Workbook()
# grab the active worksheet
ws = wb.active
# Data can be assigned directly to cells
ws['A1'] = 42
ws['B1'] = 'Tim'
# Rows can also be appended
ws.append([1, 2, 3])
# Python types will automatically be converted
import datetime
ws['A2'] = datetime.datetime.now()
# Save the file
wb.save("sample.xlsx")
```
## 74. 處理 Word 檔 (使用第三方套件流程示範)
```python=
from docx import Document
from docx.shared import Inches
document = Document()
document.add_heading('這是python操作word範例', 0)
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='Intense Quote')
document.add_paragraph(
'first item in unordered list', style='List Bullet'
)
document.add_paragraph(
'first item in ordered list', style='List Number'
)
# document.add_picture('monty-truth.png', width=Inches(1.25))
records = (
(3, '101', 'Spam'),
(7, '422', 'Eggs'),
(4, '631', 'Spam, spam, eggs, and spam')
)
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
row_cells = table.add_row().cells
row_cells[0].text = str(qty)
row_cells[1].text = id
row_cells[2].text = desc
document.add_page_break()
document.save('demo.docx')
```
## 75. 製作圖表 - (使用第三方套件流程示範)
```python=
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19680821)
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
# plt.show()
plt.savefig('123.png')
```
## 78. 寄送簡訊 - (如何寫自己的程式示範)
```python=
from twilio.rest import Client
# Your Account SID from twilio.com/console
account_sid = "ACc96364796c8a19c486cfc236560cc8ce"
# Your Auth Token from twilio.com/console
auth_token = "33cce26bc4f7a610d8b2176a94f66273"
client = Client(account_sid, auth_token)
message = client.messages.create(
to="+886988247111",
from_="+12183927353",
body="Hello from Python!-Tim")
print(message.sid)
```
## 84. [專案實作] LINE聊天機器人 - part1
* **SDK ( Software Development Kit )**
```python=
from flask import Flask, request, abort
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage,
)
app = Flask(__name__)
line_bot_api = LineBotApi('') # YOUR_CHANNEL_ACCESS_TOKEN
handler = WebhookHandler('') # YOUR_CHANNEL_SECRET
@app.route("/callback", methods=['POST'])
def callback():
# get X-Line-Signature header value
signature = request.headers['X-Line-Signature']
# get request body as text
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
# handle webhook body
try:
handler.handle(body, signature)
except InvalidSignatureError:
print("Invalid signature. Please check your channel access token/channel secret.")
abort(400)
return 'OK'
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=event.message.text))
if __name__ == "__main__":
app.run()
```
## 85. [專案實作] LINE聊天機器人 - part2
* Procfile # Heroku使用
```
web gunicorn app:app
```
* requirement # 版本需求
```
line-bot-sdk
gunicorn
flask
```
## 86. [專案實作] LINE聊天機器人 - part3
* rule-based (if, elif, else)
* 非rule-based (AI)
## 88. [進階] Class 類別 part 2 - 如何寫class
```python=
# class 類別(種類)
# 在pyhton的世界裡,所有東西都是物件(object)
class Student:
def __init__(self, name, score): # initialize 初始化
self.name = name # 兩種屬性:function, 非function
self.score = score
print('我誕生了')
self.do_hw()
def do_hw(self):
print('我在做作業')
def study(self):
print('我在讀書')
self.score += 5
def sleep(self):
print('I am sleeping!')
s1 = Student('Tim', 83)
s2 = Student('John', 75)
print(s1.name, s1.score)
print(s2.name, s2.score)
s2.study()
print(s2.name, s2.score)
```
## 89. [進階] Class 類別 part 3 - 神秘的self
```python=
```
```python=
```