源:pypypypy
www.cnblogs.com/pypypy/p/12011506.html
內置函數就是python給你提供的, 拿來直接用的函數,比如print.,input等。截止到python版本3.6.2 python一共提供了68個內置函數。
#68個內置函數
# abs dict help min setattr
# all dir hex next slice
# any divmod id object sorted
# ascii enumerate input oct staticmethod
# bin eval int open str
# bool exec isinstance ord sum
# bytearray ?lter issubclass pow super
# bytes ?oat iter print tuple
# callable format len property type
# chr frozenset list range vars
# classmethod getattr locals repr zip
# compile globals map reversed __import__
# complex hasattr max round
# delattr hash memoryview set
和數字相關
1. 數據類型
bool : 布爾型(True,False)
int : 整型(整數)
float : 浮點型(小數)
complex : 復數
2. 進制轉換
bin 將給的參數轉換成二進制
otc 將給的參數轉換成八進制
hex 將給的參數轉換成十六進制
print(bin(10)) # 二進制:0b1010
print(hex(10)) # 十六進制:0xa
print(oct(10)) # 八進制:0o12
3. 數學運算
abs 返回絕對值
divmode 返回商和余數
round 四舍五入
pow(a, b) 求a的b次冪, 如果有三個參數. 則求完次冪后對第三個數取余
sum 求和
min 求最小值
max 求最大值
print(abs(-2)) # 絕對值:2
print(divmod(20,3)) # 求商和余數:(6,2)
print(round(4.50)) # 五舍六入:4
print(round(4.51)) #5
print(pow(10,2,3)) # 如果給了第三個參數. 表示最后取余:1
print(sum([1,2,3,4,5,6,7,8,9,10])) # 求和:55
print(min(5,3,9,12,7,2)) #求最小值:2
print(max(7,3,15,9,4,13)) #求最大值:15
和數據結構相關
1. 序列
(1)列表和元組
list 將一個可迭代對象轉換成列表
tuple 將一個可迭代對象轉換成元組
print(list((1,2,3,4,5,6))) #[1, 2, 3, 4, 5, 6]
print(tuple([1,2,3,4,5,6])) #(1, 2, 3, 4, 5, 6)
(2)相關內置函數
reversed 將一個序列翻轉, 返回翻轉序列的迭代器
slice 列表的切片
lst="你好啊"
it=reversed(lst) # 不會改變原列表. 返回一個迭代器, 設計上的一個規則
print(list(it)) #['啊', '好', '你']
lst=[1, 2, 3, 4, 5, 6, 7]
print(lst[1:3:1]) #[2,3]
s=slice(1, 3, 1) # 切片用的
print(lst[s]) #[2,3]
(3)字符串
str 將數據轉化成字符串
print(str(123)+'456') #123456
format 與具體數據相關, 用于計算各種小數, 精算等.
s="hello world!"
print(format(s, "^20")) #劇中
print(format(s, "<20")) #左對齊
print(format(s, ">20")) #右對齊
# hello world!
# hello world!
# hello world!
print(format(3, 'b' )) # 二進制:11
print(format(97, 'c' )) # 轉換成unicode字符:a
print(format(11, 'd' )) # ?進制:11
print(format(11, 'o' )) # 八進制:13
print(format(11, 'x' )) # 十六進制(?寫字母):b
print(format(11, 'X' )) # 十六進制(大寫字母):B
print(format(11, 'n' )) # 和d?樣:11
print(format(11)) # 和d?樣:11
print(format(123456789, 'e' )) # 科學計數法. 默認保留6位小數:1.234568e+08
print(format(123456789, '0.2e' )) # 科學計數法. 保留2位小數(小寫):1.23e+08
print(format(123456789, '0.2E' )) # 科學計數法. 保留2位小數(大寫):1.23E+08
print(format(1.23456789, 'f' )) # 小數點計數法. 保留6位小數:1.234568
print(format(1.23456789, '0.2f' )) # 小數點計數法. 保留2位小數:1.23
print(format(1.23456789, '0.10f')) # 小數點計數法. 保留10位小數:1.2345678900
print(format(1.23456789e+3, 'F')) # 小數點計數法. 很大的時候輸出INF:1234.567890
bytes 把字符串轉化成bytes類型
bs=bytes("今天吃飯了嗎", encoding="utf-8")
print(bs) #b'\xe4\xbb\x8a\xe5\xa4\xa9\xe5\x90\x83\xe9\xa5\xad\xe4\xba\x86\xe5\x90\x97'
bytearray 返回一個新字節數組. 這個數字的元素是可變的, 并且每個元素的值得范圍是[0,256)
ret=bytearray("alex" ,encoding='utf-8')
print(ret[0]) #97
print(ret) #bytearray(b'alex')
ret[0]=65 #把65的位置A賦值給ret[0]
print(str(ret)) #bytearray(b'Alex')
ord 輸入字符找帶字符編碼的位置
chr 輸入位置數字找出對應的字符
ascii 是ascii碼中的返回該值 不是就返回u
print(ord('a')) # 字母a在編碼表中的碼位:97
print(ord('中')) # '中'字在編碼表中的位置:20013
print(chr(65)) # 已知碼位,求字符是什么:A
print(chr(19999)) #丟
for i in range(65536): #打印出0到65535的字符
print(chr(i), end=" ")
print(ascii("@")) #'@'
repr 返回一個對象的string形式
s="今天\n吃了%s頓\t飯" % 3
print(s)#今天# 吃了3頓 飯
print(repr(s)) # 原樣輸出,過濾掉轉義字符 \n \t \r 不管百分號%
#'今天\n吃了3頓\t飯'
2. 數據集合
字典:dict 創建一個字典
集合:set 創建一個集合
frozenset 創建一個凍結的集合,凍結的集合不能進行添加和刪除操作。
3. 相關內置函數
len 返回一個對象中的元素的個數
sorted 對可迭代對象進行排序操作 (lamda)
語法:sorted(Iterable, key=函數(排序規則), reverse=False)
Iterable: 可迭代對象
key: 排序規則(排序函數), 在sorted內部會將可迭代對象中的每一個元素傳遞給這個函數的參數. 根據函數運算的結果進行排序
reverse: 是否是倒敘. True: 倒敘, False: 正序
lst=[5,7,6,12,1,13,9,18,5]
lst.sort # sort是list里面的一個方法
print(lst) #[1, 5, 5, 6, 7, 9, 12, 13, 18]
ll=sorted(lst) # 內置函數. 返回給你一個新列表 新列表是被排序的
print(ll) #[1, 5, 5, 6, 7, 9, 12, 13, 18]
l2=sorted(lst,reverse=True) #倒序
print(l2) #[18, 13, 12, 9, 7, 6, 5, 5, 1]
#根據字符串長度給列表排序
lst=['one', 'two', 'three', 'four', 'five', 'six']
def f(s):
return len(s)
l1=sorted(lst, key=f, )
print(l1) #['one', 'two', 'six', 'four', 'five', 'three']
enumerate 獲取集合的枚舉對象
lst=['one','two','three','four','five']
for index, el in enumerate(lst,1): # 把索引和元素一起獲取,索引默認從0開始. 可以更改
print(index)
print(el)
# 1
# one
# 2
# two
# 3
# three
# 4
# four
# 5
# five
all 可迭代對象中全部是True, 結果才是True
any 可迭代對象中有一個是True, 結果就是True
print(all([1,'hello',True,9])) #True
print(any([0,0,0,False,1,'good'])) #True
zip 函數用于將可迭代的對象作為參數, 將對象中對應的元素打包成一個元組, 然后返回由這些元組組成的列表. 如果各個迭代器的元素個數不一致, 則返回列表長度與最短的對象相同
lst1=[1, 2, 3, 4, 5, 6]
lst2=['醉鄉民謠', '驢得水', '放牛班的春天', '美麗人生', '辯護人', '被嫌棄的松子的一生']
lst3=['美國', '中國', '法國', '意大利', '韓國', '日本']
print(zip(lst1, lst1, lst3)) #<zip object at 0x00000256CA6C7A88>
for el in zip(lst1, lst2, lst3):
print(el)
# (1, '醉鄉民謠', '美國')
# (2, '驢得水', '中國')
# (3, '放牛班的春天', '法國')
# (4, '美麗人生', '意大利')
# (5, '辯護人', '韓國')
# (6, '被嫌棄的松子的一生', '日本')
fiter 過濾 (lamda)
語法:fiter(function. Iterable)
function: 用來篩選的函數. 在?lter中會自動的把iterable中的元素傳遞給function. 然后根據function返回的True或者False來判斷是否保留留此項數據 , Iterable: 可迭代對象
def func(i): # 判斷奇數
return i % 2==1
lst=[1,2,3,4,5,6,7,8,9]
l1=filter(func, lst) #l1是迭代器
print(l1) #<filter object at 0x000001CE3CA98AC8>
print(list(l1)) #[1, 3, 5, 7, 9]
map 會根據提供的函數對指定序列列做映射(lamda)
語法 : map(function, iterable)
可以對可迭代對象中的每一個元素進行映射. 分別去執行 function
def f(i): return i
lst=[1,2,3,4,5,6,7,]
it=map(f, lst) # 把可迭代對象中的每一個元素傳遞給前面的函數進行處理. 處理的結果會返回成迭代器print(list(it)) #[1, 2, 3, 4, 5, 6, 7]
和作用域相關
locals 返回當前作用域中的名字
globals 返回全局作用域中的名字
def func:
a=10
print(locals) # 當前作用域中的內容
print(globals) # 全局作用域中的內容
print("今天內容很多")
func
# {'a': 10}
# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':
# <_frozen_importlib_external.SourceFileLoader object at 0x0000026F8D566080>,
# '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins'
# (built-in)>, '__file__': 'D:/pycharm/練習/week03/new14.py', '__cached__': None,
# 'func': <function func at 0x0000026F8D6B97B8>}
# 今天內容很多
和迭代器/生成器相關
range 生成數據
next 迭代器向下執行一次, 內部實際使?用了__ next__?方法返回迭代器的下一個項目
iter 獲取迭代器, 內部實際使用的是__ iter__?方法來獲取迭代器
for i in range(15,-1,-5):
print(i)
# 15
# 10
# 5
# 0
lst=[1,2,3,4,5]
it=iter(lst) # __iter__獲得迭代器
print(it.__next__) #1
print(next(it)) #2 __next__
print(next(it)) #3
print(next(it)) #4
字符串類型代碼的執行
eval 執行字符串類型的代碼. 并返回最終結果
exec 執行字符串類型的代碼
compile 將字符串類型的代碼編碼. 代碼對象能夠通過exec語句來執行或者eval進行求值
s1=input("請輸入a+b:") #輸入:8+9
print(eval(s1)) # 17 可以動態的執行代碼. 代碼必須有返回值
s2="for i in range(5): print(i)"
a=exec(s2) # exec 執行代碼不返回任何內容
# 0
# 1
# 2
# 3
# 4
print(a) #None
# 動態執行代碼
exec("""
def func:
print(" 我是周杰倫")
""" )
func #我是周杰倫
code1="for i in range(3): print(i)"
com=compile(code1, "", mode="exec") # compile并不會執行你的代碼.只是編譯
exec(com) # 執行編譯的結果
# 0
# 1
# 2
code2="5+6+7"
com2=compile(code2, "", mode="eval")
print(eval(com2)) # 18
code3="name=input('請輸入你的名字:')" #輸入:hello
com3=compile(code3, "", mode="single")
exec(com3)
print(name) #hello
輸入輸出
print : 打印輸出
input : 獲取用戶輸出的內容
print("hello", "world", sep="*", end="@") # sep:打印出的內容用什么連接,end:以什么為結尾
#hello*world@
內存相關
hash : 獲取到對象的哈希值(int, str, bool, tuple). hash算法:(1) 目的是唯一性 (2) dict 查找效率非常高, hash表.用空間換的時間 比較耗費內存
s='alex'
print(hash(s)) #-168324845050430382
lst=[1, 2, 3, 4, 5]
print(hash(lst)) #報錯,列表是不可哈希的
id : 獲取到對象的內存地址
s='alex'
print(id(s)) #2278345368944
文件操作相關
open : 用于打開一個文件, 創建一個文件句柄
f=open('file',mode='r',encoding='utf-8')
f.read
f.close
模塊相關
__ import__ : 用于動態加載類和函數
# 讓用戶輸入一個要導入的模塊
import os
name=input("請輸入你要導入的模塊:")
__import__(name) # 可以動態導入模塊
幫 助
help : 函數用于查看函數或模塊用途的詳細說明
print(help(str)) #查看字符串的用途
調用相關
callable : 用于檢查一個對象是否是可調用的. 如果返回True, object有可能調用失敗, 但如果返回False. 那調用絕對不會成功
a=10
print(callable(a)) #False 變量a不能被調用
#
def f:
print("hello")
print(callable(f)) # True 函數是可以被調用的
查看內置屬性
dir : 查看對象的內置屬性, 訪問的是對象中的__dir__方法
print(dir(tuple)) #查看元組的方法
質文章,第一時間送達!
作者 | Erik-Jan van Baaren
策劃 | 萬佳
出處 | 架構頭條
全球各地的程序員都是怎樣使用 Python?
我們從最常用的 Python 包入手,去解答上述這個問題。最初,我列出過去一年在 PyPI 上下載次數最多的 Python 包。接下來,深入研究其用途、它們之間的關系和它們備受歡迎的原因。
1 Urllib3
下載次數:8.93 億
Urllib3是一個 Python 的 HTTP 客戶端,它擁有 Python 標準庫中缺少的許多功能:
不要被名字所誤導,Urllib3并不是urllib2的后繼者,而后者是 Python 核心的一部分。如果你想使用盡可能多的 Python 核心功能,或者你能安裝什么東西是受限,那么請查看 urlllib.request。
https://docs.python.org/3/library/urllib.request.html#module-urllib.request
對最終用戶來說,我強烈建議使用 requests 包(參閱列表中的 #6)。這個包之所以會排名第一,是因為有差不多 1200 個包依賴 urllib3,其中許多包在這個列表中的排名也很高。
https://libraries.io/pypi/urllib3/dependents
2 Six
下載次數:7.32 億
six 是一個是 Python 2 和 3 的兼容性庫。這個項目旨在支持可同時運行在 Python 2 和 3 上的代碼庫。
它提供了許多可簡化 Python 2 和 3 之間語法差異的函數。一個容易理解的例子是six.print_。在 Python 3 中,打印是通過print函數完成的,而在 Python 2 中,print后面沒有括號。因此,有了six.print_后,你就可以使用一個語句來同時支持兩種語言。
一些事實:
雖然我理解它為什么這么受歡迎,但我希望人們能完全放棄 Python 2,因為要知道從 2020 年 1 月 1 日起 Python 2 的官方支持就已停止。
PyPI 頁面
https://pypi.org/project/six/
文檔
https://six.readthedocs.io/
3 botocore、boto3、s3transfer、awscli
這里,我把相關的幾個項目列在一起:
botocore(#3,6.6 億次下載)
s3transfer(#7,5.84 億次下載)
awscli(#17,3.94 億次下載)
boto3(#22,3.29 億次下載)
Botocore是 AWS 的底層接口。Botocore是 Boto3 庫(#22)的基礎,后者讓你可以使用 Amazon S3 和 Amazon EC2 一類的服務。Botocore 還是 AWS-CLI 的基礎,后者為 AWS 提供統一的命令行界面。
S3transfer(#7)是用于管理 Amazon S3 傳輸的 Python 庫。它正在積極開發中,其介紹頁面不推薦人們現在使用,或者至少等版本固定下來再用,因為其 API 可能發生變化,在次要版本之間都可能更改。Boto3、AWS-CLI和其他許多項目都依賴s3transfer。
令人驚訝的是,這些針對 AWS 庫的排名竟如此之高——這充分說明了 AWS 有多厲害。
4 Pip
下載次數:6.27 億
我想,你們大多數人都知道并且很喜歡 pip,它是 Python 的包安裝器。你可以用 pip 輕松地從 Python 包索引和其他索引(例如本地鏡像或帶有私有軟件的自定義索引)來安裝軟件包。
有關 pip 的一些有趣事實:
https://medium.com/better-programming/stop-installing-python-packages-globally-use-virtual-environments-a31dee9fb2de
5 Python-dateutil
下載次數:6.17 億
python-dateutil模塊提供了對標準datetime模塊的強大擴展。我的經驗是,常規的Python datetime缺少哪些功能,python-dateutil就能補足那一塊。
你可以用這個庫做很多很棒的事情。其中,我發現的一個特別有用的功能就是:模糊解析日志文件中的日期,例如:
from dateutil.parser import parse logline='INFO 2020-01-01T00:00:01 Happy new year, human.'timestamp=parse(log_line, fuzzy=True)print(timestamp)# 2020-01-01 00:00:01
6 Requests
下載次數:6.11 億
Requests建立在我們的 #1 庫——urllib3基礎上。它讓 Web 請求變得非常簡單。相比urllib3來說,很多人更喜歡這個包。而且使用它的最終用戶可能也比urllib3更多。后者更偏底層,并且考慮到它對內部的控制級別,它一般是作為其他項目的依賴項。
下面這個例子說明 requests 用起來有多簡單:
import requests r=requests.get('https://api.github.com/user', auth=('user', 'pass'))r.status_code# 200r.headers['content-type']# 'application/json; charset=utf8'r.encoding# 'utf-8'r.text# u'{"type":"User"...'r.json# {u'disk_usage': 368627, u'private_gists': 484, ...}
PyPI 頁面
https://pypi.org/project/requests
文檔
https://2.python-requests.org/en/master/
7 S3transfer
這里把 #3、#7、#17 和 #22 放在一起介紹,因為它們的關系非常密切。
8 Certifi
下載次數:5.52 億
近年來,幾乎所有網站都轉向 SSL,你可以通過地址欄中的小鎖符號來識別它。加了小鎖意味著與該站點的通信是安全和加密的,能防止竊聽行為。
小鎖告訴我們此網站已使用 SSL 保護
加密過程是基于 SSL 證書的,并且這些 SSL 證書由受信任的公司或非營利組織(如 LetsEncrypt)創建。這些組織使用他們的(中間)證書對這些證書進行數字簽名。
你的瀏覽器使用這些證書的公開可用部分來驗證這些簽名,這樣就能確保你正查看的是真實內容,并且沒有人能窺探到通信數據。Python 軟件也能做同樣事情。這就是 certifi 的用途所在。它與 Chrome、Firefox 和 Edge 等網絡瀏覽器隨附的根證書集合沒有太大區別。
Certifi是根證書的一個精選集合,有了它,你的 Python 代碼就能驗證 SSL 證書的可信度。
如此處所示,許多項目信任并依賴 certifi。這也是該項目排名如此之高的原因所在。
https://libraries.io/pypi/certifi/dependents
certifi PyPI 頁面
https://pypi.org/project/certifi/
文檔
https://certifiio.readthedocs.io/en/latest/
9 Idna
下載次數:5.27 億
根據其 PyPI 頁面,idna提供了“對 RFC5891 中指定的應用程序中國際化域名(IDNA)協議的支持?!?/p>
可能你像我一樣也是一頭霧水,不知道Idna是什么,有什么用!據悉,應用程序中的國際化域名(IDNA)是一種用來處理包含非 ASCII 字符的域名機制。但是,原始域名系統已經提供對基于非 ASCII 字符的域名支持。所以,哪有問題?
問題在于應用程序(例如電子郵件客戶端和 Web 瀏覽器)不支持非 ASCII 字符。更具體地說,電子郵件和 HTTP 用的協議不支持這些字符。對許多國家來說,這沒什么問題,但是像中國、俄羅斯、德國、希臘和印度尼西亞等國家,這是個問題。最后,來自這些地方的一群聰明人想到 IDNA。
IDNA的核心是兩個函數:ToASCII和ToUnicode。ToASCII會將國際 Unicode 域轉換為 ASCII 字符串。ToUnicode則逆轉該過程。在IDNA包中,這些函數稱為idna.encode和idna.decode,如以下代碼片段所示:
import idnaidna.encode('ドメイン.テスト')# b'xn--eckwd4c7c.xn--zckzah'print(idna.decode('xn--eckwd4c7c.xn--zckzah'))# ドメイン.テスト
如果你是受虐狂,則可以閱讀 RFC-3490 了解這一編碼的詳細信息。
PyPI 頁面
https://pypi.org/project/idna/
GitHub 頁面
https://github.com/kjd/idna
10 PyYAML
下載次數:5.25 億
YAML是一種數據序列化格式。它的設計宗旨是讓人類和計算機都能很容易地閱讀代碼——人類很容易讀寫它的內容,計算機也可以解析它。
PyYAML是 Python 的YAML解析器和發射器,這意味著它可以讀寫YAML。它會把任何 Python 對象寫成YAML:列表、字典,甚至是類實例都包括在內。
Python 提供了自己的配置解析器,但是與 Python 的ConfigParser的基本.ini文件結構相比,YAML 提供更多功能。
https://docs.python.org/3/library/configparser.html
例如,YAML可以存儲任何數據類型:布爾值、列表、浮點數等等。ConfigParser會將所有內容存儲為內部字符串。如果要使用ConfigParser加載整數,則你需要指定自己要顯式獲取一個int:
config.getint(“section”, “my_int”)
pyyaml能自動識別類型,所以這將使用PyYAML返回你的int:
config[“section”][“my_int”]
YAML還允許任意的 deep trees,雖然不是每個項目都需要這種東西,但是需要時,它就可以派上用場。你可能有自己的偏好,但是許多項目都使用YAML作為配置文件,所以這個項目是很受歡迎的。
PyPI 頁面
https://pypi.org/project/PyYAML/
文檔
https://pyyaml.org/
11 Pyasn1
下載次數:5.12 億
像上面的IDNA一樣,這個項目也非常有用:
ASN.1 類型和 DER/BER/CER 編碼(X.208)的純 Python 實現
所幸這個已有數十年歷史的標準有很多信息可用。ASN.1是 Abstract Syntax Notation One 的縮寫,它就像是數據序列化的教父。它來自電信行業。也許你知道協議緩沖區或 Apache Thrift?這就是它們的 1984 年版本。
ASN.1 描述了系統之間的跨平臺接口,以及可以通過該接口發送的數據結構。
還記得 Certifi(請參閱 #8)嗎?ASN.1 用于定義 HTTPS 協議和其他許多加密系統中使用的證書格式。它也用在了 SNMP、LDAP、Kerberos、UMTS、LTE 和 VOIP 協議中。
這是一個非常復雜的規范,并且某些實現已被證明滿是漏洞。你可能還會喜歡關于 ASN.1 的這個有趣的 Reddit 帖子。
https://www.reddit.com/r/programming/comments/1hf7ds/useful_old_technologies_asn1/
一個建議,除非你真的需要,否則還是敬而遠之吧。但由于它用在很多地方,因此許多包都依賴這個包。
12 Docutils
下載次數:5.08 億
Docutils是一個模塊化系統,用來將純文本文檔處理為很多有用的格式,例如 HTML、XML 和 LaTeX 等。Docutils能讀取reStructuredText格式的純文本文檔,這種格式是類似于 MarkDown 的易讀標記語法。
你可能聽說過,甚至讀過 PEP 文檔。
https://www.python.org/dev/peps/pep-0012/
那么什么是 PEP 文檔?最早的 PEP 文檔,PEP-1 為我們提供很好的解釋:
PEP 的意思是 Python 增強提案。一個 PEP 就是一個設計文檔,用來向 Python 社區提供信息,或描述 Python 或其過程或環境的新功能。PEP 應該提供該功能的簡明技術規范以及功能的原理。
PEP 文檔使用固定的reStructuredText模板編寫,并使用docutils轉換為格式正確的文檔。
Docutils 也是Sphinx的核心。Sphinx用于創建文檔項目。如果Docutils是一臺機器,則Sphinx就是工廠。它最初是為了構建 Python 文檔而創建的,但其他許多項目也使用它為代碼提供文檔。你可能已經讀過 readthedocs.org 上的文檔,那里的大多數文檔都是由Sphinx和docutils創建的。
13Chardet
下載次數:5.01 億
你可以用chardet模塊來檢測文件或數據流的字符集。比如說,需要分析大量隨機文本時,這會很有用。但你也可以在處理遠程下載的數據,但不知道用的是什么字符集時使用它。
安裝chardet后,你還有一個名為chardetect的命令行工具,用法如下:
chardetect somefile.txtsomefile.txt: ascii with confidence 1.0
你還能通過編程方式使用這個庫,具體參閱文檔。Chardet是requests等許多包的需求。我覺得沒有多少人會單獨使用chardet,所以它這么流行肯定是因為這些依賴項。
https://chardet.readthedocs.io/en/latest/usage.html
14 RSA
下載次數:4.92 億
rsa包是一個純 Python 的 RSA 實現。它支持:
它既可以用作 Python 庫,也能在命令行中使用。
一些事實:
以下代碼段展示了如何在一個非常簡單的用例中使用 RSA:
import rsa # Bob creates a key pair:(bob_pub, bob_priv)=rsa.newkeys(512) # Alice ecnrypts a message for Bob# with his public keycrypto=rsa.encrypt('hello Bob!', bob_pub) # When Bob gets the message, he# decrypts it with his private key:message=rsa.decrypt(crypto, bob_priv)print(message.decode('utf8'))# hello Bob!
假設 Bob 保留自己的私鑰 private,那么 Alice 可以確定他是唯一可以閱讀該消息的人。但是,Bob 不能確定是 Alice 發送了該消息,因為任何人都可以獲取并使用他的公鑰。為證明是她,Alice 可以用她的私鑰在郵件上簽名。Bob 可以用她的公鑰驗證此簽名,確保消息的確是她發送的。
諸如google-auth(#37)、oauthlib(#54)、awscli(#17)之類的包都依賴rsa包。很少有人會將這個工具獨立使用,因為有更快、更原生的替代方法。
15 Jmespath
下載次數:4.73 億
在 Python 中用 JSON 非常容易,因為它在 Python 字典上的映射非常好。對我來說,這是它最好的特性之一。
實話實說——盡管我已經用 JSON 做過很多工作,但我從未聽說過這個包。我只是用 json.loads 并從字典中手動獲取數據,也許再搞個循環什么的。
JMESPath,發音為“James path”,使 Python 中的 JSON 更容易使用。它允許你聲明性地指定如何從 JSON 文檔中提取元素。以下是一些基本示例:
import jmespath # Get a specific elementd={"foo": {"bar": "baz"}}print(jmespath.search('foo.bar', d))# baz # Using a wildcard to get all namesd={"foo": {"bar": [{"name": "one"}, {"name": "two"}]}}print(jmespath.search('foo.bar[*].name', d))# [“one”, “two”]
PyPI 頁面
https://pypi.org/project/jmespath/
文檔
http://jmespath.org/
16 Setuptools
下載次數:4.01 億
它是用于創建 Python 包的工具。不過,其文檔很糟糕。它沒有清晰描述它的用途,并且文檔中包含無效鏈接。最好的信息源是這個站點,特別是這個創建 Python 包的指南。
https://packaging.python.org/
https://packaging.python.org/tutorials/packaging-projects/
17 Awscli
這里把 #3、#7、#17 和 #22 放在一起介紹,因為它們的關系非常密切。
18 Pytz
下載次數:3.94 億次
像dateutils(#5)一樣,這個庫可幫助你處理日期和時間。有時候,時區處理起來可能很麻煩。幸好有這樣的包,可以讓事情變得簡單些。
我自己關于計算機上處理時間的經驗總結來說是:始終在內部使用 UTC。僅當生成供人類讀取的輸出時,才轉換為本地時間。
這是pytz用法的示例:
from datetime import datetimefrom pytz import timezone amsterdam=timezone('Europe/Amsterdam') ams_time=amsterdam.localize(datetime(2002, 10, 27, 6, 0, 0))print(ams_time)# 2002-10-27 06:00:00+01:00 # It will also know when it's Summer Time# in Amsterdam (similar to Daylight Savings Time):ams_time=amsterdam.localize(datetime(2002, 6, 27, 6, 0, 0))print(ams_time)# 2002-06-27 06:00:00+02:00
19 Futures
下載次數:3.89 億
從 Python 3.2 開始,python 提供current.futures模塊,可幫助你實現異步執行。futures 包是該庫適用于 Python 2 的 backport。它不適用于 Python3 用戶,因為 Python 3 原生提供了該模塊。
正如我之前提到的,從 2020 年 1 月 1 日起,Python 2 的官方支持停止。希望我明年重新再來看的時候,這個包不會再出現在前 22 名中吧。
下面是 futures 的基本示例:
from concurrent.futures import ThreadPoolExecutorfrom time import sleep def return_after_5_secs(message): sleep(5) return message pool=ThreadPoolExecutor(3) future=pool.submit(return_after_5_secs, ("Hello world")) print(future.done)# Falsesleep(5)print(future.done)# Trueprint(future.result)# Hello World
如你所見,你可以創建一個線程池并提交一個要由這些線程之一執行的函數。同時,你的程序將繼續在主線程中運行。這是并行執行程序的簡便方法。
20 Colorama
下載次數:3.7 億
使用 Colorama,你可以為終端添加一些顏色:
https://pypi.org/project/colorama/
這樣做起來非常容易,具體請查看以下示例代碼:
from colorama import Fore, Back, Style print(Fore.RED + 'some red text')print(Back.GREEN + 'and with a green background')print(Style.DIM + 'and in dim text')print(Style.RESET_ALL)print('back to normal now')
21 Simplejson
下載次數:3.41 億
原生的json模塊有什么問題,才需要這種高級替代方案呢?并沒有!實際上,Python 的json就是simplejson。但是simplejson也有一些優點:
你經常會在支持 JSON 的腳本中看到以下內容:
try: import simplejson as jsonexcept ImportError: import json
除非你需要標準庫中所沒有的內容,否則我只會使用json。Simplejson可以比json快很多,因為它有一些用 C 實現的部分。除非你正在處理成千上萬個 JSON 文件,否則這種優勢對你來說不是什么大事。還可以看看 UltraJSON,它應該更快一些,因為它幾乎所有的代碼都是用 C 編寫的。
22 Boto3
這里把 #3、#7、#17 和 #22 放在一起介紹,因為它們的關系非常密切。
23 小結
僅僅介紹這 22 個包恐怕不夠,因為排在后面的許多包都是像我們這樣最終用戶感興趣的。
通過制作這份列表,我了解到一些新東西:
延展閱讀:
https://medium.com/better-programming/the-22-most-used-python-packages-in-the-world-7020a904b2e
下是爬取京東商品詳情的Python3代碼,以excel存放鏈接的方式批量爬取。excel如下
代碼如下
私信小編01即可獲取大量Python學習資源
from selenium import webdriver
from lxml import etree
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import datetime
import calendar
import logging
from logging import handlers
import requests
import os
import time
import pymssql
import openpyxl
import xlrd
import codecs
class EgongYePing:
options=webdriver.FirefoxOptions()
fp=webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","application/zip,application/octet-stream")
global driver
driver=webdriver.Firefox(firefox_profile=fp,options=options)
def Init(self,url,code):
print(url.strip())
driver.get(url.strip())
#driver.refresh()
# 操作瀏覽器屬于異步,在網絡出現問題的時候。可能代碼先執行。但是請求頁面沒有應答。所以硬等
time.sleep(int(3))
html=etree.HTML(driver.page_source)
if driver.title!=None:
listImg=html.xpath('//*[contains(@class,"spec-list")]//ul//li//img')
if len(listImg)==0:
pass
if len(listImg)>0:
imgSrc=''
for item in range(len(listImg)):
imgSrc='https://img14.360buyimg.com/n0/'+listImg[item].attrib["data-url"]
print('頭圖下載:'+imgSrc)
try:
Headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}
r=requests.get(imgSrc, headers=Headers, stream=True)
if r.status_code==200:
imgUrl=''
if item==0:
imgUrl+=code + "_主圖_" + str(item) + '.' + imgSrc.split('//')[1].split('/')[len(imgSrc.split('//')[1].split('/'))-1].split('.')[1]
else:
imgUrl+=code + "_附圖_" + str(item) + '.' + imgSrc.split('//')[1].split('/')[len(imgSrc.split('//')[1].split('/'))-1].split('.')[1]
open(os.getcwd()+'/img/'+ imgUrl , 'wb').write(r.content) # 將內容寫入圖片
del r
except Exception as e:
print("圖片禁止訪問:"+imgSrc)
listImg=html.xpath('//*[contains(@class,"ssd-module")]')
if len(listImg)==0:
listImg=html.xpath('//*[contains(@id,"J-detail-content")]//div//div//p//img')
if len(listImg)==0:
listImg=html.xpath('//*[contains(@id,"J-detail-content")]//img')
if len(listImg)>0:
for index in range(len(listImg)):
detailsHTML=listImg[index].attrib
if 'data-id' in detailsHTML:
try:
details=driver.find_element_by_class_name("animate-"+listImg[index].attrib['data-id']).value_of_css_property('background-image')
details=details.replace('url(' , ' ')
details=details.replace(')' , ' ')
newDetails=details.replace('"', ' ')
details=newDetails.strip()
print("詳情圖下載:"+details)
try:
Headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}
r=requests.get(details, headers=Headers, stream=True)
if r.status_code==200:
imgUrl=''
imgUrl+=code + "_詳情圖_" + str(index) + '.' + details.split('//')[1].split('/')[len(details.split('//')[1].split('/'))-1].split('.')[1]
open(os.getcwd()+'/img/'+ imgUrl, 'wb').write(r.content) # 將內容寫入圖片
del r
except Exception as e:
print("圖片禁止訪問:"+details)
except Exception as e:
print('其他格式的圖片不收錄');
if 'src' in detailsHTML:
try:
details=listImg[index].attrib['src']
if 'http' in details:
pass
else:
details='https:'+details
print("詳情圖下載:"+details)
try:
Headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}
r=requests.get(details, headers=Headers, stream=True)
if r.status_code==200:
imgUrl=''
imgUrl+=code + "_詳情圖_" + str(index) + '.' + details.split('//')[1].split('/')[len(details.split('//')[1].split('/'))-1].split('.')[1]
open(os.getcwd()+'/img/'+ imgUrl, 'wb').write(r.content) # 將內容寫入圖片
del r
except Exception as e:
print("圖片禁止訪問:"+details)
except Exception as e:
print('其他格式的圖片不收錄');
print('結束執行')
@staticmethod
def readxlsx(inputText):
filename=inputText
inwb=openpyxl.load_workbook(filename) # 讀文件
sheetnames=inwb.get_sheet_names() # 獲取讀文件中所有的sheet,通過名字的方式
ws=inwb.get_sheet_by_name(sheetnames[0]) # 獲取第一個sheet內容
# 獲取sheet的最大行數和列數
rows=ws.max_row
cols=ws.max_column
for r in range(1,rows+1):
for c in range(1,cols):
if ws.cell(r,c).value!=None and r!=1 :
if 'item.jd.com' in str(ws.cell(r,c+1).value) and str(ws.cell(r,c+1).value).find('i-item.jd.com')==-1:
print('支持:'+str(ws.cell(r,c).value)+'|'+str(ws.cell(r,c+1).value))
EgongYePing().Init(str(ws.cell(r,c+1).value),str(ws.cell(r,c).value))
else:
print('當前格式不支持:'+(str(ws.cell(r,c).value)+'|'+str(ws.cell(r,c+1).value)))
pass
pass
if __name__=="__main__":
start=EgongYePing()
start.readxlsx(r'C:\Users\newYear\Desktop\爬圖.xlsx')
基本上除了過期的商品無法訪問以外。對于京東的三種頁面結構都做了處理。能訪問到的商品頁面。還做了模擬瀏覽器請求訪問和下載?;静粫环磁老x屏蔽下載。
上面這一段是以火狐模擬器運行
上面這一段是模擬瀏覽器下載。如果不加上這一段。經常會下載幾十張圖片后,很長一段時間無法正常下載圖片。因為沒有請求頭被認為是爬蟲。
上面這段是京東的商品詳情頁面,經常會三種?(可能以后會更多的頁面結構)
所以做了三段解析。只要沒有抓到圖片就換一種解析方式。這楊就全了。
京東的圖片基本只存/1.jpg。然后域名是 https://img14.360buyimg.com/n0/。所以目前要拼一下。
京東還有個很蛋疼的地方是圖片以data-id拼進div的背景元素里。所以取出來的時候要繞一下。還好也解決了。
以下是爬取京東商品詳情的Python3代碼,以excel存放鏈接的方式批量爬取。excel如下
因為這次是淘寶和京東一起爬取。所以在一個excel里。代碼里區分淘寶和京東的鏈接。以下是代碼
from selenium import webdriver
from lxml import etree
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import datetime
import calendar
import logging
from logging import handlers
import requests
import os
import time
import pymssql
import openpyxl
import xlrd
import codecs
class EgongYePing:
options=webdriver.FirefoxOptions()
fp=webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","application/zip,application/octet-stream")
global driver
driver=webdriver.Firefox(firefox_profile=fp,options=options)
def Init(self,url,code):
#driver=webdriver.Chrome('D:\python3\Scripts\chromedriver.exe')
#driver.get(url)
print(url.strip())
driver.get(url.strip())
#driver.refresh()
# 操作瀏覽器屬于異步,在網絡出現問題的時候??赡艽a先執行。但是請求頁面沒有應答。所以硬等
time.sleep(int(3))
html=etree.HTML(driver.page_source)
if driver.title!=None:
listImg=html.xpath('//*[contains(@id,"J_UlThumb")]//img')
if len(listImg)==0:
pass
if len(listImg)>0:
imgSrc=''
for item in range(len(listImg)):
search=listImg[item].attrib
if 'data-src' in search:
imgSrc=listImg[item].attrib["data-src"].replace('.jpg_50x50','')
else:
imgSrc=listImg[item].attrib["src"]
if 'http' in imgSrc:
pass
else:
imgSrc='https:'+imgSrc
print('頭圖下載:'+imgSrc)
try:
Headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}
r=requests.get(imgSrc, headers=Headers, stream=True)
if r.status_code==200:
imgUrl=''
if item==0:
imgUrl+=code + "_主圖_" + str(item) + '.' + imgSrc.split('//')[1].split('/')[len(imgSrc.split('//')[1].split('/'))-1].split('.')[1]
else:
imgUrl+=code + "_附圖_" + str(item) + '.' + imgSrc.split('//')[1].split('/')[len(imgSrc.split('//')[1].split('/'))-1].split('.')[1]
open(os.getcwd()+'/img/'+ imgUrl , 'wb').write(r.content) # 將內容寫入圖片
del r
except Exception as e:
print("圖片禁止訪問:"+imgSrc)
listImg=html.xpath('//*[contains(@id,"J_DivItemDesc")]//img')
if len(listImg)>0:
for index in range(len(listImg)):
detailsHTML=listImg[index].attrib
if 'data-ks-lazyload' in detailsHTML:
details=listImg[index].attrib["data-ks-lazyload"]
print("詳情圖下載:"+details)
else:
details=listImg[index].attrib["src"]
print("詳情圖下載:"+details)
try:
Headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}
r=requests.get(details, headers=Headers, stream=True)
if r.status_code==200:
imgUrl=''
details=details.split('?')[0]
imgUrl+=code + "_詳情圖_" + str(index) + '.' + details.split('//')[1].split('/')[len(details.split('//')[1].split('/'))-1].split('.')[1]
open(os.getcwd()+'/img/'+ imgUrl, 'wb').write(r.content) # 將內容寫入圖片
del r
except Exception as e:
print("圖片禁止訪問:"+details)
print('結束執行')
@staticmethod
def readxlsx(inputText):
filename=inputText
inwb=openpyxl.load_workbook(filename) # 讀文件
sheetnames=inwb.get_sheet_names() # 獲取讀文件中所有的sheet,通過名字的方式
ws=inwb.get_sheet_by_name(sheetnames[0]) # 獲取第一個sheet內容
# 獲取sheet的最大行數和列數
rows=ws.max_row
cols=ws.max_column
for r in range(1,rows+1):
for c in range(1,cols):
if ws.cell(r,c).value!=None and r!=1 :
if 'item.taobao.com' in str(ws.cell(r,c+1).value):
print('支持:'+str(ws.cell(r,c).value)+'|'+str(ws.cell(r,c+1).value))
EgongYePing().Init(str(ws.cell(r,c+1).value),str(ws.cell(r,c).value))
else:
print('當前格式不支持:'+(str(ws.cell(r,c).value)+'|'+str(ws.cell(r,c+1).value)))
pass
pass
if __name__=="__main__":
start=EgongYePing()
start.readxlsx(r'C:\Users\newYear\Desktop\爬圖.xlsx')
淘寶有兩個問題,一個是需要綁定賬號登錄訪問。這里是代碼斷點。然后手動走過授權。
第二個是被休息和懶惰加載。被休息。其實沒影響的。一個頁面結構已經加載出來了。然后也不會影響訪問其他的頁面。
至于懶惰加載嘛。對我們也沒啥影響。如果不是直接寫在src里那就在判斷一次取 data-ks-lazyload就出來了。
最后就是爬取的片段截圖
建議還是直接將爬取的數據存服務器,數據庫,或者圖片服務器。因為程序挺靠譜的。一萬條數據。爬了26個G的文件。最后上傳的時候差點累死了
是真的大。最后還要拆包。十幾個2g壓縮包一個一個上傳。才成功。
*請認真填寫需求信息,我們會在24小時內與您取得聯系。