Hi 大家好,
今天要開始介紹Python中的常用內建模組篇,那我們開始吧!
math
模組提供基本的數學函數和常數,常用於進行數學計算,如平方根、三角函數、對數等。import math
# 計算平方根
sqrt_value = math.sqrt(25)
print("Square Root:", sqrt_value)
# 計算餘弦值
cos_value = math.cos(math.radians(30))
print("Cosine Value:", cos_value)
PS D:\Project\practice> python hi.py
Square Root: 5.0
Cosine Value: 0.8660254037844387
PS D:\Project\practice>
re
模組用於正則表達式的操作,用來作為字串匹配和搜索功能。import re
# 搜尋字串中的數字
pattern = r'\d+'
text = "The order number is 88888, hello"
result = re.search(pattern, text)
if result:
print("Found number:", result.group())
PS D:\Project\practice> python hi.py
Found number: 88888
PS D:\Project\practice>
datetime
模組用於處理日期和時間,提供日期、時間操作及格式化等功能。from datetime import datetime
# 取得當前時間
now = datetime.now()
print("Current DateTime:", now)
# 格式化時間
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted DateTime:", formatted_time)
PS D:\Project\practice> python hi.py
Current DateTime: 2024-08-30 15:14:50.326371
Formatted DateTime: 2024-08-30 15:14:50
PS D:\Project\practice>
urllib
模組提供處理URL的工具,包含網路請求、解析URL等功能,經常使用在網路操作。import urllib.request
# 從URL下載內容
url = 'https://tcgbusfs.blob.core.windows.net/dotapp/youbike/v2/youbike_immediate.json'
response = urllib.request.urlopen(url)
web_content = response.read().decode('utf-8')
print("YouBike 2.0 臺北市公共自行車即時資訊:", web_content)
PS D:\Project\practice> python hi.py
[{"sno":"500101001","sna":"YouBike2.0_捷運科技大樓站","sarea":"大安區","mday":"2024-08-30 15:15:22","ar":"復興南路二段235號前","sareaen":"Daan Dist.","snaen":"YouBike2.0_MRT Technology Bldg. Sta.","aren":"No.235, Sec. 2, Fuxing S. Rd.","act":"1","srcUpdateTime":"2024-08-30 15:16:24","updateTime":"2024-08-30 15:16:52","infoTime":"2024-08-30 15:15:22","infoDate":"2024-08-30","total":28,"available_rent_bikes":5,"latitude":25.02605,"longitude":121.5436,"available_return_bikes":23},{"sno":"500101002","sna":"YouBike2.0_復興南路二段273號前","sarea":"大安區","mday":"2024-08-30 15:15:22","ar":"復興南路二段273號西側","sareaen":"Daan Dist.","snaen":"YouBike2.0_No.273, Sec. 2, Fuxing S. Rd.","aren":"No.273, Sec. 2, Fuxing S. Rd. (West)","act":"1","srcUpdateTime":"2024-08-30 15:16:24","updateTime":"2024-08-30 15:16:52","infoTime":"2024-08-30 15:15:22","infoDate":"2024-08-30","total":21,"available_rent_bikes":4,"latitude":25.02565,"longitude":121.54357,"available_return_bikes":17}.......
random
模組提供隨機數產生和隨機選取一元素,常用於模擬隨機行為。import random
# 生成隨機整數
random_int = random.randint(1, 10)
print("Random Integer:", random_int)
# 隨機選取一個元素
choices = ['aaaaa', 'bbbbbb', 'xxxxxxx', 'zzzzzz']
selected = random.choice(choices)
print("Random Choice:", selected)
PS D:\Project\practice> python hi.py
Random Integer: 8
Random Choice: zzzzzz
PS D:\Project\practice> python hi.py
Random Integer: 10
Random Choice: xxxxxxx
PS D:\Project\practice>
json
模組用於處理JSON格式的資料,支援JSON的解析和序列化,常用於處理API返回的數據。import json
# 將字典轉換為JSON字串
data = {'myname': 'EricHsu', 'age': 30}
json_string = json.dumps(data)
print("JSON String:", json_string)
# 將JSON字串轉換為字典
parsed_data = json.loads(json_string)
print("Parsed Data:", parsed_data)
PS D:\Project\practice> python hi.py
JSON String: {"myname": "EricHsu", "age": 30}
Parsed Data: {'myname': 'EricHsu', 'age': 30}
PS D:\Project\practice>
csv
模組用於處理CSV文件,可以讀取和寫入CSV格式的資料,常用於處理表格數據。data.csv內容
name,age,city
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago
import csv
# 讀取CSV文件
with open('data.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print("Row:", row)
# 寫入CSV文件
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['name', 'age'])
writer.writerow(['Erichsu', 35])
PS D:\Project\practice> python hi.py
Row: ['name', 'age', 'city']
Row: ['Alice', '30', 'New York']
Row: ['Bob', '25', 'Los Angeles']
Row: ['Charlie', '35', 'Chicago']
PS D:\Project\practice>
output.csv 檔案內容
name,age
Erichsu,35
那今天就是我參加鐵人賽的最後一天,很高興自己能完成30天的挑戰,表示自己增加了持之以恆的技能點數+1,之後還要持續的學習和應用Python來開發更多的案例。
感謝大家的閱讀,我們下次見^^b!!