Python 是一種高級編程語言,以其簡潔清晰的語法和強大的功能被廣泛應用于各種領域,包括自動化腳本編寫、數據分析、機器學習、Web開發等。以下是一些關于使用 Python 編寫腳本工具的基本介紹、常用庫以及一些實用技巧總結。
這里寫目錄標題
- 基礎知識
- 安裝 Python
- 第一個 Python 腳本
- 常用庫
- 實用技巧
基礎知識
安裝 Python
首先需要安裝 Python 環境。可以從 Python官方網站 下載適合你操作系統的最新版本,并按照提示進行安裝。
第一個 Python 腳本
創建一個簡單的 Python 腳本文件(如 hello.py
),并在其中輸入以下內容:
print("Hello, World!")
然后在命令行中運行該腳本:
python hello.py
常用庫
Python 擁有豐富的標準庫和第三方庫,可以幫助你快速實現各種功能。以下是幾個常用的庫及其應用場景:
-
os 和 sys
- 用于與操作系統交互。
import os import sys# 獲取當前工作目錄 print(os.getcwd())# 列出指定目錄下的所有文件 for file in os.listdir('/path/to/directory'):print(file)# 獲取命令行參數 print(sys.argv)
-
shutil
- 提供了高級文件操作功能,如復制、移動和刪除文件或目錄。
import shutil# 復制文件 shutil.copy('source_file.txt', 'destination_file.txt')# 移動文件 shutil.move('source_file.txt', 'new_location/source_file.txt')# 刪除目錄及其內容 shutil.rmtree('directory_to_remove')
-
subprocess
- 用于調用外部命令并獲取輸出結果。
import subprocess# 執行命令并捕獲輸出 result = subprocess.run(['ls', '-l'], capture_output=True, text=True) print(result.stdout)
-
argparse
- 解析命令行參數。
import argparseparser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('integers', metavar='N', type=int, nargs='+',help='an integer for the accumulator') parser.add_argument('--sum', dest='accumulate', action='store_const',const=sum, default=max,help='sum the integers (default: find the max)')args = parser.parse_args() print(args.accumulate(args.integers))
-
pandas
- 數據分析和處理的強大工具,特別適用于表格數據。
import pandas as pd# 創建 DataFrame df = pd.DataFrame({'A': ['foo', 'bar', 'baz'],'B': [1, 2, 3] })# 查看前幾行數據 print(df.head())# 進行數據篩選 filtered_df = df[df['B'] > 1] print(filtered_df)
-
requests
- 發送 HTTP 請求并處理響應。
import requestsresponse = requests.get('https://api.github.com/events') print(response.status_code) print(response.json())
-
smtplib
- 發送電子郵件。
import smtplib from email.mime.text import MIMETextmsg = MIMEText('This is the body of the email') msg['Subject'] = 'Test Email' msg['From'] = 'from@example.com' msg['To'] = 'to@example.com'with smtplib.SMTP('smtp.example.com') as server:server.login('username', 'password')server.send_message(msg)
實用技巧
-
虛擬環境
- 使用虛擬環境管理項目的依賴關系,避免不同項目之間的依賴沖突。
python -m venv myenv source myenv/bin/activate # Linux/MacOS myenv\Scripts\activate # Windows
-
日志記錄
- 使用
logging
模塊記錄程序運行時的信息,便于調試和維護。
import logginglogging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__)logger.debug('Debug message') logger.info('Info message') logger.warning('Warning message') logger.error('Error message') logger.critical('Critical message')
- 使用
-
異常處理
- 使用
try-except
結構捕捉和處理異常。
try:x = 1 / 0 except ZeroDivisionError as e:print(f"Caught an exception: {e}") finally:print("This will always execute")
- 使用
-
上下文管理器
- 使用
with
語句自動管理資源,確保資源正確釋放。
with open('file.txt', 'r') as f:content = f.read()print(content)
- 使用
-
列表推導式
- 使用列表推導式簡化代碼,提高可讀性和效率。
numbers = [1, 2, 3, 4, 5] squares = [x**2 for x in numbers if x % 2 == 0] print(squares) # 輸出: [4, 16]
-
使用PYTHON 進行CSV文件的數據處理demo
import numpy as np #導入numpy庫,用于計算 import pandas as pd #導入pandas庫,用于CSV文件處理 import matplotlib.pyplot as plt #導入matplotlib.pyplot庫,用于繪圖 from matplotlib.pylab import mpl #導入mpl函數,用于顯示中文和負號mpl.rcParams['font.sans-serif'] = ['SimHei'] #顯示中文 mpl.rcParams['axes.unicode_minus']=False #顯示負號path = 'test.csv' #csv文件路徑 data = pd.read_csv(path) #讀取 csv文件Before_result = data['BEFORE'] #導出BEFORE列的數據 BEFORE為第一行數據,也是索引 After_result = data['AFTER'] #導出AFTER列的數據 Delta_result = data['DELTA'] #導出DELTA列的數據N = 500 t = np.arange(N)+1 #得到1:500的數據plt.figure() plt.plot(t,Before_result, 'b.-') plt.title('Before_result') plt.show()plt.figure() plt.plot(t,After_result, 'b.-') plt.title('After_result') plt.show()plt.figure() plt.plot(t,Delta_result, 'b.-') plt.title('Delta_result') plt.show()
-
計算指數和取整
- 使用 math.pow() 函數Python 的 math 模塊也提供了一個 pow() 函數,它可以用于浮點數的冪運算。需要注意的是,math.pow() 總是返回一個浮點數。
- 請注意,由于 math.pow() 返回的是浮點數,所以在處理整數指數時可能會有精度損失或不必要的浮點數表示。
import math result = math.pow(2, exponent) print(round(1.4)) # 輸出: 1 print(round(1.5)) # 輸出: 2 print(round(1.6)) # 輸出: 2 print(round(1.23, 1)) # 輸出: 1.2 print(round(1.27, 1)) # 輸出: 1.3
-
十六進制轉換
- 函數hex() 是 Python 內置的一個函數,可以直接將整數轉換為以 ‘0x’ 開頭的小寫十六進制字符串。
- 語法:hex(number)?number:需要轉換為十六進制的十進制整數。decimal_number = 255
hexadecimal_string = hex(decimal_number)print(hexadecimal_string) # 輸出: 0xff
- python如果你不想讓結果包含 ‘0x’ 前綴,可以使用切片操作去除它:
hexadecimal_string_no_prefix = hex(decimal_number)[2:]print(hexadecimal_string_no_prefix) # 輸出: ff
-
FFT分析
import numpy as np #數值計算庫 from scipy.fftpack import fft #基于 Numpy 的科學計算庫,用于數學、科學、工程學等領域 import matplotlib.pyplot as plt #MATLAB類似的繪圖API from matplotlib.pylab import mpl #許多NumPy和pyplot模塊中常用的函數,方便用戶快速進行計算和繪圖mpl.rcParams['font.sans-serif'] = ['SimHei'] # 顯示中文 mpl.rcParams['axes.unicode_minus'] = False # 顯示負號# 采樣點選擇1400個,因為設置的信號頻率分量最高為600赫茲,根據采樣定理知采樣頻率要大于信號頻率2倍, # 所以這里設置采樣頻率為1400赫茲(即一秒內有1400個采樣點,一樣意思的) N = 1400 x = np.linspace(0, 1, N)# 設置需要采樣的信號,頻率分量有0,200,400和600 y = 7 * np.sin(2 * np.pi * 200 * x) + 5 * np.sin(2 * np.pi * 400 * x) + 3 * np.sin(2 * np.pi * 600 * x) + 10fft_y = fft(y) # 快速傅里葉變換x = np.arange(N) # 頻率個數 half_x = x[range(int(N / 2))] # 取一半區間angle_y = np.angle(fft_y) # 取復數的角度abs_y = np.abs(fft_y) # 取復數的絕對值,即復數的模(雙邊頻譜) normalization_y = abs_y / (N / 2) # 歸一化處理(雙邊頻譜) normalization_y[0] /= 2 # 歸一化處理(雙邊頻譜) normalization_half_y = normalization_y[range(int(N / 2))] # 由于對稱性,只取一半區間(單邊頻譜)plt.subplot(231) plt.plot(x, y) plt.title('原始波形')plt.subplot(232) plt.plot(x, fft_y, 'black') plt.title('雙邊振幅譜(未求振幅絕對值)', fontsize=9, color='black')plt.subplot(233) plt.plot(x, abs_y, 'r') plt.title('雙邊振幅譜(未歸一化)', fontsize=9, color='red')plt.subplot(234) plt.plot(x, angle_y, 'violet') plt.title('雙邊相位譜(未歸一化)', fontsize=9, color='violet')plt.subplot(235) plt.plot(x, normalization_y, 'g') plt.title('雙邊振幅譜(歸一化)', fontsize=9, color='green')plt.subplot(236) plt.plot(half_x, normalization_half_y, 'blue') plt.title('單邊振幅譜(歸一化)', fontsize=9, color='blue')plt.show()