Python常用的模塊非常多,主要分為內置模塊和第三方模塊兩大類,且不同模塊應用場景不同又可以分為文本類、數據結構類、數學運算類、文件系統類、爬蟲類、網絡通訊類等多個類型。
大家常用的內置模塊比如:math、re、datetime、urllib、os、random等,第三方模塊比如pandas、numpy、requests、matplotlib等。
模塊是將復雜的、同一應用領域的功能代碼進行封裝,你只需要調用接口,輸入相應參數,便可以輕松拿到結果,類似瑞士軍刀、萬能工具箱。
內置模塊,顧名思義就是Python軟件內嵌的模塊,無需額外安裝。
想要了解詳細的內置模塊,最好去Python官網看,挺詳細的。
https://docs.python.org/zh-cn/3/library/index.html。
你也可以在代碼行輸入print(help(modules)),會顯示全部的內置模塊。
這里舉幾個常用的內置模塊,并附上代碼:
用來進行數學計算,它提供了很多數學方面的專業函數,適合科研、算法。
import math# 計算平方根sqrt_value = math.sqrt(25)print("Square Root:", sqrt_value)# 計算正弦值sin_value = math.sin(math.radians(30))print("Sine Value:", sin_value)
正則表達式在Python中的擴展實現,該模塊能支持正則表達式幾乎所有語法,對于文本處理來說必不可少。
import re# 查找匹配的字符串pattern = r"/d+"text = "There are 123 apples and 456 oranges."matches = re.findall(pattern, text)print("Matches:", matches)
用于處理日期和時間,這個模塊非常實用!
import datetime# 獲取當前日期和時間current_datetime = datetime.datetime.now()print("Current Date and Time:", current_datetime)# 格式化日期時間formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")print("Formatted Date and Time:", formatted_datetime)
用于進行網絡請求,獲取網頁HTML,所謂的爬蟲就是這個模塊。
import urllib.request# 發起HTTP GET請求response = urllib.request.urlopen("https://www.example.com")html = response.read()print("HTML Content:", html[:100])
提供了與操作系統交互的功能,比如文件和目錄操作。
import os# 獲取當前工作目錄current_dir = os.getcwd()print("Current Directory:", current_dir)# 列出目錄中的文件和子目錄files_and_dirs = os.listdir(current_dir)print("Files and Directories:", files_and_dirs)
用于生成偽隨機數。
import random# 生成隨機整數random_integer = random.randint(1, 10)print("Random Integer:", random_integer)# 從列表中隨機選擇元素random_element = random.choice(["apple", "banana", "cherry"])print("Random Element:", random_element)
專門用來處理 JSON 格式數據。
import json# 將字典轉換為 JSON 格式的字符串data = {"name": "Alice", "age": 25}json_string = json.dumps(data)print("JSON String:", json_string)# 將 JSON 格式的字符串轉換為字典parsed_data = json.loads(json_string)print("Parsed Data:", parsed_data)
提供了一些除list、dict之外有用的數據容器,比如 defaultdict、Counter 等。
from collections import defaultdict, Counter# 創建默認字典word_counts = defaultdict(int)words = ["apple", "banana", "apple", "cherry", "banana", "apple"]for word in words: word_counts[word] += 1print("Word Counts:", word_counts)# 統計元素出現的次數element_counts = Counter(words)print("Element Counts:", element_counts)
專門用于處理逗號分隔值(CSV)文件。
import re# 查找匹配的字符串pattern = r"/d+"text = "There are 123 apples and 456 oranges."matches = re.findall(pattern, text)print("Matches:", matches)
提供了與Python解釋器交互的功能,例如訪問命令行參數。
import sys# 獲取命令行參數arguments = sys.argvprint("Command-line Arguments:", arguments)
Python之所以這么受歡迎,很大一部分原因得益于強大的第三方工具生態,幾乎各個領域都有對應的模塊可以使用。
比如
其他各領域都有相應的模塊可以使用,這里就不一一列舉。
總得來說,Python常用的模塊非常多,還是要根據你的使用場景來選擇,大家可以去Python官網、github上找相應的模塊及教程。
本文鏈接:http://www.www897cc.com/showinfo-26-39530-0.html我常用的幾個經典Python模塊
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com