Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º²...

141
1.1 1.2 1.3 1.3.1 1.3.2 1.3.3 1.3.4 1.3.5 1.3.6 1.3.6.1 1.3.6.2 1.3.7 1.3.7.1 1.3.7.1.1 1.3.7.1.2 1.3.7.2 1.3.7.3 1.3.8 1.3.8.1 1.3.8.2 1.3.9 1.4 1.4.1 1.4.2 1.4.3 1.4.4 1.4.5 1.4.6 1.5 1.5.1 ⽬录 前⾔ 背景 常⽤代码段 通⽤逻辑 变量 系统 ⽇期时间 字符和字符串 ⽂件系统 ⽂件 ⽂件夹 多媒体 图像 Pillow 百度OCR ⾳频 视频 ⽹络相关 BeautifulSoup requests 数学 常⻅语法 函数参数 dict字典 list列表和set集合 sort排序 enum枚举 collections集合 附录 参考资料 1

Transcript of Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º²...

Page 1: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

1.1

1.2

1.3

1.3.1

1.3.2

1.3.3

1.3.4

1.3.5

1.3.6

1.3.6.1

1.3.6.2

1.3.7

1.3.7.1

1.3.7.1.1

1.3.7.1.2

1.3.7.2

1.3.7.3

1.3.8

1.3.8.1

1.3.8.2

1.3.9

1.4

1.4.1

1.4.2

1.4.3

1.4.4

1.4.5

1.4.6

1.5

1.5.1

⽬录

前⾔

背景

常⽤代码段

通⽤逻辑

变量

系统

⽇期时间

字符和字符串

⽂件系统

⽂件

⽂件夹

多媒体

图像

Pillow

百度OCR

⾳频

视频

⽹络相关

BeautifulSoup

requests

数学

常⻅语法

函数参数

dict字典

list列表和set集合

sort排序

enum枚举

collections集合

附录

参考资料

1

Page 2: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

2

Page 3: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

Python常⽤代码段

最新版本: v1.2

更新时间: 20210114

简介

整理出crifan总结的Python各个⽅⾯常⽤的代码段,供需要的参考。包括通⽤逻辑、变量、系统、⽇期

时间、字符和字符串、⽂件系统,⽐如⽂件和⽂件夹等、以及第三⽅库,⽐如BeautifulSoup、以及多

媒体⾳视频类、包括Pillow、以及⽹络的Requests等;以及其他常⻅语法,包括dict字典、list列表、

set集合、enum枚举、collections集合等。

源码+浏览+下载

本书的各种源码、在线浏览地址、多种格式⽂件下载如下:

Gitbook源码

crifan/python_common_code_snippet:Python常⽤代码段

如何使⽤此Gitbook源码去⽣成发布为电⼦书

详⻅:crifan/gitbook_template:demohowtousecrifangitbooktemplateanddemo

在线浏览

Python常⽤代码段book.crifan.comPython常⽤代码段crifan.github.io

离线下载阅读

Python常⽤代码段PDFPython常⽤代码段ePubPython常⽤代码段Mobi

版权说明

此电⼦书教程的全部内容,如⽆特别说明,均为本⼈原创和整理。其中部分内容参考⾃⽹络,均已备

注了出处。如有发现侵犯您版权,请通过邮箱联系我 admin艾特crifan.com,我会尽快删除。谢谢

合作。

鸣谢

前⾔

3

Page 4: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

感谢我的⽼婆陈雪的包容理解和悉⼼照料,才使得我 crifan有更多精⼒去专注技术专研和整理归纳出

这些电⼦书和技术教程,特此鸣谢。

更多其他电⼦书

本⼈ crifan还写了其他 100+本电⼦书教程,感兴趣可移步⾄:

crifan/crifan_ebook_readme:Crifan的电⼦书的使⽤说明

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2021-01-1711:54:16

前⾔

4

Page 5: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

背景

多年的技术开发,积累了很多关于Python的常⽤的⼀些函数和功能,都已整理到对应的函数库中:

https://github.com/crifan/crifanLibPython

且也给出了很多函数的demo演示如何使⽤:

https://github.com/crifan/crifanLibPython/tree/master/crifanLib/demo

但还是解释的不够清楚和全⾯。

故此处专⻔把Python的常⽤的代码段和调⽤举例,都整理⾄此,详细解释。

⽬的:

⽅便需要时能快速查阅:直接看代码,⼀看就懂,⽆需额外解释。

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

背景

5

Page 6: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

常⽤代码段

下⾯总结各个⽅⾯的Python常⽤代码段。

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

常⽤代码段

6

Page 7: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

通⽤逻辑

多次运⾏⼀个函数,直到成功运⾏

执⾏⼀个函数(可能有多个可变数量的参数),且尝试多次,直到成功或超出最⼤此时,最终实现

是:

defdefmultipleRetrymultipleRetry((functionInfoDictfunctionInfoDict,,maxRetryNummaxRetryNum==55,,sleepIntervalsleepInterval==0.10.1,,isShowErrWhenFailisShowErrWhenFail==TrTrueue))::""""""dosomething,retrymutipletimeiffaildosomething,retrymutipletimeiffail

Args:Args:functionInfoDict(dict):functioninfodictcontainfunctionCallbackand[optionalfunctionInfoDict(dict):functioninfodictcontainfunctionCallbackand[optional]functionParaDict]functionParaDictmaxRetryNum(int):maxretrynumbermaxRetryNum(int):maxretrynumbersleepInterval(float):sleeptimeofeachintervalwhenfailsleepInterval(float):sleeptimeofeachintervalwhenfailisShowErrWhenFail(bool):showerrorwhenfailiftrueisShowErrWhenFail(bool):showerrorwhenfailiftrueReturns:Returns:boolboolRaises:Raises:""""""doSuccessdoSuccess==FalseFalsefunctionCallbackfunctionCallback==functionInfoDictfunctionInfoDict[["functionCallback""functionCallback"]]functionParaDictfunctionParaDict==functionInfoDictfunctionInfoDict..getget(("functionParaDict""functionParaDict",,NoneNone))

curRetryNumcurRetryNum==maxRetryNummaxRetryNumwhilewhilecurRetryNumcurRetryNum>>00::ififfunctionParaDictfunctionParaDict::doSuccessdoSuccess==functionCallbackfunctionCallback((****functionParaDictfunctionParaDict))elseelse::doSuccessdoSuccess==functionCallbackfunctionCallback(())

ififdoSuccessdoSuccess::breakbreak

timetime..sleepsleep((sleepIntervalsleepInterval))curRetryNumcurRetryNum-=-=11

ififnotnotdoSuccessdoSuccess::ififisShowErrWhenFailisShowErrWhenFail::functionNamefunctionName==strstr((functionCallbackfunctionCallback))#'<boundmethodDevicesMethods.switchToAppStoreSearchTabof<src.AppCrawler.A#'<boundmethodDevicesMethods.switchToAppStoreSearchTabof<src.AppCrawler.AppCrawlerobjectat0x1053abe80>>'ppCrawlerobjectat0x1053abe80>>'logginglogging..errorerror(("Stillfailafter%dretryfor%s""Stillfailafter%dretryfor%s",,maxRetryNummaxRetryNum,,functionNamefunctionName))returnreturndoSuccessdoSuccess

说明:

通⽤逻辑

7

Page 8: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

functionCallback函数类型都要符合:返回值是bool类型才可以

调⽤举例:

(1)没有额外参数

foundAndClickedWififoundAndClickedWifi==CommonUtilsCommonUtils..multipleRetrymultipleRetry(({{"functionCallback""functionCallback"::selfself..iOSFromSettingsIiOSFromSettingsIntoWifiListntoWifiList}}))

其中:

defdefiOSFromSettingsIntoWifiListiOSFromSettingsIntoWifiList((selfself))::。。。。。。

foundAndClickedWififoundAndClickedWifi==selfself..findAndClickElementfindAndClickElement((queryquery==wifiTextQuerywifiTextQuery,,timeouttimeout==0.10.1))returnreturnfoundAndClickedWififoundAndClickedWifi

类似例⼦:

isSwitchOkisSwitchOk==selfself..multipleRetrymultipleRetry(({{"functionCallback""functionCallback"::selfself..switchToAppStoreSearchTabswitchToAppStoreSearchTab}}))

对⽐之前原始写法:

isSwitchOkisSwitchOk==selfself..switchToAppStoreSearchTabswitchToAppStoreSearchTab(())

其他类似例⼦:

foundAndClickedDownloadfoundAndClickedDownload==selfself..multipleRetrymultipleRetry(({{"functionCallback""functionCallback"::selfself..appStoreStartDownloappStoreStartDownloadad}}))

详⻅:

【已解决】AppStore⾃动安装iOS的app:逻辑优化加等待和多试⼏次

(2)有额外参数,参数个数:2个

searchInputQuerysearchInputQuery=={{"type""type"::"XCUIElementTypeSearchField""XCUIElementTypeSearchField",,"name""name"::"AppStore""AppStore"}}isInputOkisInputOk==CommonUtilsCommonUtils..multipleRetrymultipleRetry(({{"functionCallback""functionCallback"::selfself..wait_element_setTextwait_element_setText,,"functionParaDict""functionParaDict"::{{"locator""locator"::searchInputQuerysearchInputQuery,,"text""text"::appNameappName,,}}}}))

对⽐之前原始写法:

通⽤逻辑

8

Page 9: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

searchInputQuerysearchInputQuery=={{"type""type"::"XCUIElementTypeSearchField""XCUIElementTypeSearchField",,"name""name"::"AppStore""AppStore"}}isInputOkisInputOk==selfself..wait_element_setTextwait_element_setText((searchInputQuerysearchInputQuery,,appNameappName))

其中wait_element_setText的定义是:

defdefwait_element_setTextwait_element_setText((selfself,,locatorlocator,,texttext))::

对应着之前传⼊时的:

"functionParaDict""functionParaDict"::{{"locator""locator"::searchInputQuerysearchInputQuery,,"text""text"::appNameappName,,}}

(3)有额外参数,且加上multipleRetry的额外参数

isSwitchOkisSwitchOk==CommonUtilsCommonUtils..multipleRetrymultipleRetry(({{"functionCallback""functionCallback"::selfself..switchToAppStoreSearchTabswitchToAppStoreSearchTab}},,maxRetryNummaxRetryNum==1010,,sleepIntervalsleepInterval==0.50.5,,))

以及类似的:

isIntoDetailOkisIntoDetailOk==selfself..multipleRetrymultipleRetry(({{"functionCallback""functionCallback"::selfself..appStoreSearchResultIntoDetailappStoreSearchResultIntoDetail,,"functionParaDict""functionParaDict"::{{"appName""appName"::appNameappName,,}}}},,sleepIntervalsleepInterval==0.50.5))

之前原始写法:

isIntoDetailOkisIntoDetailOk==selfself..appStoreSearchResultIntoDetailappStoreSearchResultIntoDetail((appNameappName))

注:

此处是后来加上的

sleepInterval=0.5

是因为后来遇到了,即使尝试了5次,依旧没找到,所以增加了没找到的延迟等待时间。

详⻅:

通⽤逻辑

9

Page 10: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

【已解决】AppStore⾃动安装iOS的app:逻辑优化加等待和多试⼏次

(4)

isIntoDetailOkisIntoDetailOk==CommonUtilsCommonUtils..multipleRetrymultipleRetry(({{"functionCallback""functionCallback"::selfself..appStoreSearchResultIntoDetailappStoreSearchResultIntoDetail,,"functionParaDict""functionParaDict"::{{"appName""appName"::appNameappName,,}}}},,maxRetryNummaxRetryNum==1010,,sleepIntervalsleepInterval==0.50.5,,))

新版:新增参数isRespFullRetValue

此处最后更新: 20200925

后续多次优化新增参数:是否返回完整信息

代码:

defdefmultipleRetrymultipleRetry((functionInfoDictfunctionInfoDict,,maxRetryNummaxRetryNum==55,,sleepIntervalsleepInterval==0.10.1,,isShowErrWhenFailisShowErrWhenFail==TrTrueue,,isRespFullRetValueisRespFullRetValue==FalseFalse))::"""dosomething,retryifsinglecallfailed,retrymutipletimeuntilmaxretrynumbe"""dosomething,retryifsinglecallfailed,retrymutipletimeuntilmaxretrynumberr

Args:Args:functionInfoDict(dict):functioninfodictcontainfunctionCallbackand[optionalfunctionInfoDict(dict):functioninfodictcontainfunctionCallbackand[optional]functionParaDict]functionParaDictmaxRetryNum(int):maxretrynumbermaxRetryNum(int):maxretrynumbersleepInterval(float):sleeptime(seconds)ofeachintervalwhenfailsleepInterval(float):sleeptime(seconds)ofeachintervalwhenfailisShowErrWhenFail(bool):showerrorwhenfailiftrueisShowErrWhenFail(bool):showerrorwhenfailiftrueisRespFullRetValue(bool):whetherreturnfullreturnvalueoffunctioncallisRespFullRetValue(bool):whetherreturnfullreturnvalueoffunctioncallReturns:Returns:isRespFullRetValue=False:boolisRespFullRetValue=False:boolisRespFullRetValue=True:bool/tuple/list/...isRespFullRetValue=True:bool/tuple/list/...Raises:Raises:""""""finalReturnValuefinalReturnValue==NoneNonedoSuccessdoSuccess==FalseFalsefunctionCallbackfunctionCallback==functionInfoDictfunctionInfoDict[["functionCallback""functionCallback"]]functionParaDictfunctionParaDict==functionInfoDictfunctionInfoDict..getget(("functionParaDict""functionParaDict",,NoneNone))

curRetryNumcurRetryNum==maxRetryNummaxRetryNumwhilewhilecurRetryNumcurRetryNum>>00::ififfunctionParaDictfunctionParaDict::#doSuccess=functionCallback(**functionParaDict)#doSuccess=functionCallback(**functionParaDict)respValuerespValue==functionCallbackfunctionCallback((****functionParaDictfunctionParaDict))elseelse::#doSuccess=functionCallback()#doSuccess=functionCallback()

通⽤逻辑

10

Page 11: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

respValuerespValue==functionCallbackfunctionCallback(())

doSuccessdoSuccess==FalseFalseififisinstanceisinstance((respValuerespValue,,boolbool))::doSuccessdoSuccess==boolbool((respValuerespValue))elifelifisinstanceisinstance((respValuerespValue,,tupletuple))::doSuccessdoSuccess==boolbool((respValuerespValue[[00]]))elifelifisinstanceisinstance((respValuerespValue,,listlist))::doSuccessdoSuccess==boolbool((respValuerespValue[[00]]))elseelse::ExceptionException(("multipleRetry:Notsupporttypeofreturnvalue:%s""multipleRetry:Notsupporttypeofreturnvalue:%s"%%respValuerespValue))

ififisRespFullRetValueisRespFullRetValue::finalReturnValuefinalReturnValue==respValuerespValueelseelse::finalReturnValuefinalReturnValue==doSuccessdoSuccess

ififdoSuccessdoSuccess::breakbreak

timetime..sleepsleep((sleepIntervalsleepInterval))curRetryNumcurRetryNum-=-=11

ififnotnotdoSuccessdoSuccess::ififisShowErrWhenFailisShowErrWhenFail::functionNamefunctionName==strstr((functionCallbackfunctionCallback))#'<boundmethodDevicesMethods.switchToAppStoreSearchTabof<src.AppCrawler.A#'<boundmethodDevicesMethods.switchToAppStoreSearchTabof<src.AppCrawler.AppCrawlerobjectat0x1053abe80>>'ppCrawlerobjectat0x1053abe80>>'logginglogging..errorerror(("Stillfailafter%dretryfor%s""Stillfailafter%dretryfor%s",,maxRetryNummaxRetryNum,,functionNamefunctionName))#returndoSuccess#returndoSuccessreturnreturnfinalReturnValuefinalReturnValue

调⽤举例:

(1)默认不返回完整信息,只返回bool值

respBoolOrTuplerespBoolOrTuple==CommonUtilsCommonUtils..multipleRetrymultipleRetry((functionInfoDictfunctionInfoDict=={{"functionCallback""functionCallback"::selfself..isGotoPayPopupPageisGotoPayPopupPage,,"functionParaDict""functionParaDict"::{{"isRespLocation""isRespLocation"::FalseFalse,,}},,}},,))

(2)返回完整信息

respBoolOrTuplerespBoolOrTuple==CommonUtilsCommonUtils..multipleRetrymultipleRetry((functionInfoDictfunctionInfoDict=={{"functionCallback""functionCallback"::selfself..isGotoPayPopupPageisGotoPayPopupPage,,"functionParaDict""functionParaDict"::{{"isRespLocation""isRespLocation"::TrueTrue,,

通⽤逻辑

11

Page 12: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

}},,}},,isRespFullRetValueisRespFullRetValue==TrueTrue,,))

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2021-01-1621:40:56

通⽤逻辑

12

Page 13: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

变量

判断变量类型

优先⽤ isinstance,⽽不是 type

>>>>>>isinstanceisinstance((22,,floatfloat))FalseFalse>>>>>>isinstanceisinstance(('a''a',,((strstr,,unicodeunicode))))TrueTrue>>>>>>isinstanceisinstance((((22,,33)),,((strstr,,listlist,,tupletuple))))TrueTrue

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

变量

13

Page 14: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

系统

此处整理⽤Python处理系统相关的通⽤的代码。

系统类型

importimportsyssys

defdefosIsWinowsosIsWinows(())::returnreturnsyssys..platformplatform===="win32""win32"

defdefosIsCygwinosIsCygwin(())::returnreturnsyssys..platformplatform===="cygwin""cygwin"

defdefosIsMacOSosIsMacOS(())::returnreturnsyssys..platformplatform===="darwin""darwin"

defdefosIsLinuxosIsLinux(())::returnreturnsyssys..platformplatform===="linux""linux"

defdefosIsAixosIsAix(())::returnreturnsyssys..platformplatform===="aix""aix"

命令⾏

获取命令⾏执⾏命令返回结果

代码:

defdefget_cmd_linesget_cmd_lines((cmdcmd,,texttext==FalseFalse))::##执⾏执⾏cmdcmd命令,将结果保存为列表命令,将结果保存为列表

resultStrresultStr==""""resultStrListresultStrList==[[]]trytry::consoleOutputByteconsoleOutputByte==subprocesssubprocess..check_outputcheck_output((cmdcmd,,shellshell==TrueTrue))#b'C02Y3N10JHC8\n'#b'C02Y3N10JHC8\n'trytry::resultStrresultStr==consoleOutputByteconsoleOutputByte..decodedecode(("utf-8""utf-8"))exceptexceptUnicodeDecodeErrorUnicodeDecodeError::#TODO:usechardetautodetectencoding#TODO:usechardetautodetectencoding#consoleOutputStr=consoleOutputByte.decode("gbk")#consoleOutputStr=consoleOutputByte.decode("gbk")resultStrresultStr==consoleOutputByteconsoleOutputByte..decodedecode(("gb18030""gb18030"))

ififnotnottexttext::resultStrListresultStrList==resultStrresultStr..splitlinessplitlines(())exceptexceptExceptionExceptionasaserrerr::printprint(("err=%swhenruncmd=%s""err=%swhenruncmd=%s"%%((errerr,,cmdcmd))))

系统

14

Page 15: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

ififtexttext::returnreturnresultStrresultStrelseelse::returnreturnresultStrListresultStrList

硬件信息

获取当前电脑(Win或Mac)的序列号

代码:

defdefgetSerialNumbergetSerialNumber((selfself))::"""getcurrentcomputerserialnumber""""""getcurrentcomputerserialnumber"""#cmd="wmicbiosgetserialnumber"#cmd="wmicbiosgetserialnumber"cmdcmd==""""ififCommonUtilsCommonUtils..osIsWinowsosIsWinows(())::#Windows#Windowscmdcmd=="wmicbiosgetserialnumber""wmicbiosgetserialnumber"elifelifCommonUtilsCommonUtils..osIsMacOSosIsMacOS(())::#macOS#macOScmdcmd=="system_profilerSPHardwareDataType|awk'/Serial/{print$4}'""system_profilerSPHardwareDataType|awk'/Serial/{print$4}'"#TODO:addsupportotherOS#TODO:addsupportotherOS#AIX:aix#AIX:aix#Linux:linux#Linux:linux#Windows/Cygwin:cygwin#Windows/Cygwin:cygwin

serialNumberserialNumber==""""lineslines==CommonUtilsCommonUtils..get_cmd_linesget_cmd_lines((cmdcmd))ififCommonUtilsCommonUtils..osIsWinowsosIsWinows(())::#Windows#WindowsserialNumberserialNumber==lineslines[[11]]elifelifCommonUtilsCommonUtils..osIsMacOSosIsMacOS(())::#macOS#macOSserialNumberserialNumber==lineslines[[00]]#C02Y3N10JHC8#C02Y3N10JHC8

returnreturnserialNumberserialNumber

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

系统

15

Page 16: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

⽇期时间

详⻅:

https://github.com/crifan/crifanLibPython/blob/master/crifanLib/crifanDatetime.py

getCurDatetimeStr⽣成当前⽇期时间字符串

defdefgetCurDatetimeStrgetCurDatetimeStr((outputFormatoutputFormat=="%Y%m%d_%H%M%S""%Y%m%d_%H%M%S"))::""""""getcurrentdatetimethenformattostringgetcurrentdatetimethenformattostring

eg:eg:20171111_22072220171111_220722

:paramoutputFormat:datetimeoutputformat:paramoutputFormat:datetimeoutputformat:return:currentdatetimeformattedstring:return:currentdatetimeformattedstring""""""curDatetimecurDatetime==datetimedatetime..nownow(())#2017-11-1122:07:22.705101#2017-11-1122:07:22.705101curDatetimeStrcurDatetimeStr==curDatetimecurDatetime..strftimestrftime((formatformat==outputFormatoutputFormat))#'20171111_220722'#'20171111_220722'returnreturncurDatetimeStrcurDatetimeStr

调⽤举例:

curDatetimeStrcurDatetimeStr==getCurDatetimeStrgetCurDatetimeStr(())#'20191219_143400'#'20191219_143400'

datetime转时间戳

importimporttimetime

defdefdatetimeToTimestampdatetimeToTimestamp((selfself,,datetimeValdatetimeVal,,withMillisecondswithMilliseconds==FalseFalse))::""""""convertdatetimevaluetotimestampconvertdatetimevaluetotimestampeg:eg:"2006-06-0100:00:00.123"->1149091200"2006-06-0100:00:00.123"->1149091200ifwithmilliseconds->1149091200123ifwithmilliseconds->1149091200123:paramdatetimeVal::paramdatetimeVal::return::return:""""""timetupleValuetimetupleValue==datetimeValdatetimeVal..timetupletimetuple(())timestampFloattimestampFloat==timetime..mktimemktime((timetupleValuetimetupleValue))#1531468736.0->10digits#1531468736.0->10digitstimestamp10DigitInttimestamp10DigitInt==intint((timestampFloattimestampFloat))#1531468736#1531468736timestampInttimestampInt==timestamp10DigitInttimestamp10DigitInt

ififwithMillisecondswithMilliseconds::

⽇期时间

16

Page 17: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

microsecondIntmicrosecondInt==datetimeValdatetimeVal..microsecondmicrosecond#817762#817762microsecondFloatmicrosecondFloat==floatfloat((microsecondIntmicrosecondInt))//floatfloat((10000001000000))#0.817762#0.817762timestampFloattimestampFloat==timestampFloattimestampFloat++microsecondFloatmicrosecondFloat#1531468736.817762#1531468736.817762timestampFloattimestampFloat==timestampFloattimestampFloat**10001000#1531468736817.7621->13digits#1531468736817.7621->13digitstimestamp13DigitInttimestamp13DigitInt==intint((timestampFloattimestampFloat))#1531468736817#1531468736817timestampInttimestampInt==timestamp13DigitInttimestamp13DigitInt

returnreturntimestampInttimestampInt

获取当前时间戳

fromfromdatetimedatetimeimportimportdatetimedatetime

defdefgetCurTimestampgetCurTimestamp((withMillisecondswithMilliseconds==FalseFalse))::""""""getcurrenttime'stimestampgetcurrenttime'stimestamp(default)notmilliseconds->10digits:1351670162(default)notmilliseconds->10digits:1351670162withmilliseconds->13digits:1531464292921withmilliseconds->13digits:1531464292921""""""curDatetimecurDatetime==datetimedatetime..nownow(())returnreturndatetimeToTimestampdatetimeToTimestamp((curDatetimecurDatetime,,withMillisecondswithMilliseconds))

时间戳精确到毫秒

fromfromdatetimedatetimeimportimportdatetimedatetime,,timedeltatimedeltatimestampStrtimestampStr==datetimedatetime..nownow(())..strftimestrftime(("%Y%m%d_%H%M%S_%f""%Y%m%d_%H%M%S_%f"))#20180712_154134_660436#20180712_154134_660436

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

⽇期时间

17

Page 18: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

字符和字符串

详⻅:

https://github.com/crifan/crifanLibPython/blob/master/crifanLib/crifanFile.py

Python3str转bytes

Python3中,把字符串转换成字节码,可以有两种写法:

⽅法1:⽤bytes去转换

convertedBytesconvertedBytes==bytesbytes((originStroriginStr))

⽅法2:⽤字符串str的编码encode

encodedBytesencodedBytes==originStroriginStr..encodeencode(())

其中:

都有额外的encoding参数:

由于默认都是UTF-8所以可加可不加

也可以根据需要,去加其他你要的编码

如果要加,就是:

convertedBytesconvertedBytes==bytesbytes((originStroriginStr,,"UTF-8""UTF-8"))encodedBytesencodedBytes==originStroriginStr..encodeencode(("UTF-8""UTF-8"))

字符串格式化为⼈类易读格式

defdefformatSizeformatSize((sizeInBytessizeInBytes,,decimalNumdecimalNum==11,,isUnitWithIisUnitWithI==FalseFalse,,sizeUnitSeperatorsizeUnitSeperator==""""))::""""""formatsizetohumanreadablestringformatsizetohumanreadablestring

example:example:3746->3.7KB3746->3.7KB87533->85.5KiB87533->85.5KiB98654->96.3KB98654->96.3KB352->352.0B352->352.0B76383285->72.84MB76383285->72.84MB763832854988542->694.70TB763832854988542->694.70TB763832854988542665->678.4199PB763832854988542665->678.4199PB

字符和字符串

18

Page 19: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

refer:refer:https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-vhttps://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-sizeersion-of-file-size""""""#https://en.wikipedia.org/wiki/Binary_prefix#Specific_units_of_IEC_60027-2_A.2_and_ISO.#https://en.wikipedia.org/wiki/Binary_prefix#Specific_units_of_IEC_60027-2_A.2_and_ISO.2FIEC_800002FIEC_80000#K=kilo,M=mega,G=giga,T=tera,P=peta,E=exa,Z=zetta,Y=yotta#K=kilo,M=mega,G=giga,T=tera,P=peta,E=exa,Z=zetta,Y=yottasizeUnitListsizeUnitList==[['''',,'K''K',,'M''M',,'G''G',,'T''T',,'P''P',,'E''E',,'Z''Z']]largestUnitlargestUnit=='Y''Y'

ififisUnitWithIisUnitWithI::sizeUnitListWithIsizeUnitListWithI==[[]]forforcurIdxcurIdx,,eachUniteachUnitininenumerateenumerate((sizeUnitListsizeUnitList))::unitWithIunitWithI==eachUniteachUnitififcurIdxcurIdx>=>=11::unitWithIunitWithI+=+='i''i'sizeUnitListWithIsizeUnitListWithI..appendappend((unitWithIunitWithI))

#sizeUnitListWithI=['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']#sizeUnitListWithI=['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']sizeUnitListsizeUnitList==sizeUnitListWithIsizeUnitListWithI

largestUnitlargestUnit+=+='i''i'

suffixsuffix=="B""B"decimalFormatdecimalFormat==".""."++strstr((decimalNumdecimalNum))++"f""f"#"#"..1f1f""finalFormatfinalFormat=="%""%"++decimalFormatdecimalFormat++sizeUnitSeperatorsizeUnitSeperator++"%s%s""%s%s"#"%.1f%s%s"#"%.1f%s%s"sizeNumsizeNum==sizeInBytessizeInBytesforforsizeUnitsizeUnitininsizeUnitListsizeUnitList::ififabsabs((sizeNumsizeNum))<<1024.01024.0::returnreturnfinalFormatfinalFormat%%((sizeNumsizeNum,,sizeUnitsizeUnit,,suffixsuffix))sizeNumsizeNum/=/=1024.01024.0returnreturnfinalFormatfinalFormat%%((sizeNumsizeNum,,largestUnitlargestUnit,,suffixsuffix))

调⽤:

defdeftestKbtestKb(())::kbSizekbSize==37463746kbStrkbStr==formatSizeformatSize((kbSizekbSize))printprint(("%s-&gt;%s""%s-&gt;%s"%%((kbSizekbSize,,kbStrkbStr))))

defdeftestItestI(())::iSizeiSize==8753387533iStriStr==formatSizeformatSize((iSizeiSize,,isUnitWithIisUnitWithI==TrueTrue))printprint(("%s-&gt;%s""%s-&gt;%s"%%((iSizeiSize,,iStriStr))))

defdeftestSeparatortestSeparator(())::seperatorSizeseperatorSize==9865498654seperatorStrseperatorStr==formatSizeformatSize((seperatorSizeseperatorSize,,sizeUnitSeperatorsizeUnitSeperator==""""))printprint(("%s-&gt;%s""%s-&gt;%s"%%((seperatorSizeseperatorSize,,seperatorStrseperatorStr))))

defdeftestBytestestBytes(())::

字符和字符串

19

Page 20: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

bytesSizebytesSize==352352bytesStrbytesStr==formatSizeformatSize((bytesSizebytesSize))printprint(("%s-&gt;%s""%s-&gt;%s"%%((bytesSizebytesSize,,bytesStrbytesStr))))

defdeftestMbtestMb(())::mbSizembSize==7638328576383285mbStrmbStr==formatSizeformatSize((mbSizembSize,,decimalNumdecimalNum==22))printprint(("%s-&gt;%s""%s-&gt;%s"%%((mbSizembSize,,mbStrmbStr))))

defdeftestTbtestTb(())::tbSizetbSize==763832854988542763832854988542tbStrtbStr==formatSizeformatSize((tbSizetbSize,,decimalNumdecimalNum==22))printprint(("%s-&gt;%s""%s-&gt;%s"%%((tbSizetbSize,,tbStrtbStr))))

defdeftestPbtestPb(())::pbSizepbSize==763832854988542665763832854988542665pbStrpbStr==formatSizeformatSize((pbSizepbSize,,decimalNumdecimalNum==44))printprint(("%s-&gt;%s""%s-&gt;%s"%%((pbSizepbSize,,pbStrpbStr))))

defdefdemoFormatSizedemoFormatSize(())::testKbtestKb(())testItestI(())testSeparatortestSeparator(())testBytestestBytes(())testMbtestMb(())testTbtestTb(())testPbtestPb(())

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

字符和字符串

20

Page 21: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

⽂件系统

详⻅:

https://github.com/crifan/crifanLibPython/blob/master/crifanLib/crifanFile.pyhttps://github.com/crifan/crifanLibPython/blob/master/crifanLib/demo/crifanFileDemo.py

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

⽂件系统

21

Page 22: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

⽂件

获取⽂件最后更新时间

importimportosos

defdefgetUpdateTimegetUpdateTime((curFileOrPathcurFileOrPath))::"""getfile/folderlatestupdatetime=modifytime"""getfile/folderlatestupdatetime=modifytime

Args:Args:curFileOrPath(str):somefileorfolderpathcurFileOrPath(str):somefileorfolderpathReturns:Returns:int:timestampintof13digit,withmillisecondsint:timestampintof13digit,withmillisecondsRaises:Raises:""""""updateTimeupdateTime==NoneNonetrytry::modifyTimemodifyTime==osos..pathpath..getmtimegetmtime((curFileOrPathcurFileOrPath))#1593748641.3270357#1593748641.3270357updateTimeupdateTime==intint((modifyTimemodifyTime**10001000))#1593748641327#1593748641327exceptexceptOSErrorOSErrorasaserrerr::errMsgerrMsg==strstr((errerr))#print("errMsg=%s"%errMsg)#print("errMsg=%s"%errMsg)passpass

returnreturnupdateTimeupdateTime

详⻅:

【已解决】Python中获取⽂件最后更新时间

提取⽂件名后缀

defdefextractSuffixextractSuffix((fileNameOrUrlfileNameOrUrl))::""""""extractfilesuffixfromnameorurlextractfilesuffixfromnameorurleg:eg:https://cdn2.qupeiyin.cn/2018-09-10/15365514898246.mp4->mp4https://cdn2.qupeiyin.cn/2018-09-10/15365514898246.mp4->mp415365514894833.srt->srt15365514894833.srt->srt""""""returnreturnfileNameOrUrlfileNameOrUrl..splitsplit(('.''.'))[[--11]]

创建空⽂件

importimportosos

⽂件

22

Page 23: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

defdefcreateEmptyFilecreateEmptyFile((fullFilenamefullFilename))::"""Createaemptyfileliketouch""""""Createaemptyfileliketouch"""filePathfilePath==osos..pathpath..dirnamedirname((fullFilenamefullFilename))#createfolderifnotexist#createfolderifnotexistififnotnotosos..pathpath..existsexists((filePathfilePath))::osos..makedirsmakedirs((filePathfilePath))

withwithopenopen((fullFilenamefullFilename,,'a''a'))::#Note:notuse'w'formaybeconflictforothersconstantlywritingtoit#Note:notuse'w'formaybeconflictforothersconstantlywritingtoitosos..utimeutime((fullFilenamefullFilename,,NoneNone))

读取⽂件⼆进制数据

defdefreadBinDataFromFilereadBinDataFromFile((fileToReadfileToRead))::"""Readbinarydatafromfile""""""Readbinarydatafromfile"""binaryDatabinaryData==NoneNonetrytry::readFpreadFp==openopen((fileToReadfileToRead,,"rb""rb"))binaryDatabinaryData==readFpreadFp..readread(())readFpreadFp..closeclose(())exceptexcept::binaryDatabinaryData==NoneNone

returnreturnbinaryDatabinaryData

调⽤:

imgBinDataimgBinData==readBinDataFromFilereadBinDataFromFile((imageFullPathimageFullPath))

保存⼆进制数据到⽂件

defdefsaveDataToFilesaveDataToFile((fullFilenamefullFilename,,binaryDatabinaryData))::"""savebinarydatainfofile""""""savebinarydatainfofile"""withwithopenopen((fullFilenamefullFilename,,'wb''wb'))asasfpfp::fpfp..writewrite((binaryDatabinaryData))fpfp..closeclose(())#print("Completesavefile%s"%fullFilename)#print("Completesavefile%s"%fullFilename)

保存json到⽂件

importimportjsonjsonimportimportcodecscodecs

defdefsaveJsonToFilesaveJsonToFile((fullFilenamefullFilename,,jsonValuejsonValue))::"""savejsondictintofile""""""savejsondictintofile"""

⽂件

23

Page 24: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

withwithcodecscodecs..openopen((fullFilenamefullFilename,,'w''w',,encodingencoding=="utf-8""utf-8"))asasjsonFpjsonFp::jsonjson..dumpdump((jsonValuejsonValue,,jsonFpjsonFp,,indentindent==22,,ensure_asciiensure_ascii==FalseFalse))#print("Completesavejson%s"%fullFilename)#print("Completesavejson%s"%fullFilename)

从⽂件中加载出json

importimportjsonjsonimportimportcodecscodecs

defdefloadJsonFromFileloadJsonFromFile((fullFilenamefullFilename))::"""loadandparsejsondictfromfile""""""loadandparsejsondictfromfile"""withwithcodecscodecs..openopen((fullFilenamefullFilename,,'r''r',,encodingencoding=="utf-8""utf-8"))asasjsonFpjsonFp::jsonDictjsonDict==jsonjson..loadload((jsonFpjsonFp))#print("Completeloadjsonfrom%s"%fullFilename)#print("Completeloadjsonfrom%s"%fullFilename)returnreturnjsonDictjsonDict

通过⼆进制⽣成⽂件类型对象

(1)Python3

importimportioio

audioBinaryDataaudioBinaryData==audioObjaudioObj..readread(())audioFileLikeObjaudioFileLikeObj==ioio..BytesIOBytesIO((audioBinaryDataaudioBinaryData))

得到对应的⽂件类型的对象的: <_io.BytesIOobjectat0x115964468>,即可去像操作⽂件⼀样去操

作这个io。

(2)Python2

importimportStringIOStringIO

audioFileLikeObjaudioFileLikeObj==StringIOStringIO..StringIOStringIO(())audioFileLikeObjaudioFileLikeObj..writewrite((audioBinaryDataaudioBinaryData))

⼀⾏代码把字符串写⼊保存到⽂件

openopen((fullFilePathfullFilePath,,"w""w"))..writewrite((fileContentStrfileContentStr))..closeclose(())

举例:

openopen(("0408_1600.xml""0408_1600.xml",,"w""w"))..writewrite((pagepage))..closeclose(())

⽂件

24

Page 25: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

给⽂件增加可执⾏权限:实现chmod+x的效果

代码:

importimportososimportimportstatstat

curStatecurState==osos..statstat((someFilesomeFile))newStatenewState==curStatecurState..st_modest_mode||statstat..S_IEXECS_IEXECosos..chmodchmod((someFilesomeFile,,newStatenewState))

再去优化为函数:

importimportososimportimportstatstat

defdefchmodAddXchmodAddX((someFilesomeFile))::"""addfileexecutablemode,likechmod+x"""addfileexecutablemode,likechmod+x

Args:Args:someFile(str):filefullpathsomeFile(str):filefullpathReturns:Returns:soupsoupRaises:Raises:""""""ififosos..pathpath..existsexists((someFilesomeFile))::ififosos..pathpath..isfileisfile((someFilesomeFile))::#addexecutable#addexecutablecurStatecurState==osos..statstat((someFilesomeFile))newStatenewState==curStatecurState..st_modest_mode||statstat..S_IEXECS_IEXECosos..chmodchmod((someFilesomeFile,,newStatenewState))

调⽤:

chmodAddXchmodAddX((shellFullPathshellFullPath))

继续优化:

参考Howdoyoudoasimple"chmod+x"fromwithinpython?-StackOverflow

如果想要加上,给任何⼈都有可执⾏权限,则可以⽤:

defdefchmodAddXchmodAddX((someFilesomeFile))::"""addfileexecutablemode,likechmod+x"""addfileexecutablemode,likechmod+x

Args:Args:someFile(str):filefullpathsomeFile(str):filefullpathReturns:Returns:soupsoupRaises:Raises:

⽂件

25

Page 26: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

""""""ififosos..pathpath..existsexists((someFilesomeFile))::ififosos..pathpath..isfileisfile((someFilesomeFile))::#addexecutable#addexecutablecurStatecurState==osos..statstat((someFilesomeFile))#STAT_OWNER_EXECUTABLE=stat.S_IEXEC#STAT_OWNER_EXECUTABLE=stat.S_IEXEC#executableMode=STAT_OWNER_EXECUTABLE#executableMode=STAT_OWNER_EXECUTABLESTAT_EVERYONE_EXECUTABLESTAT_EVERYONE_EXECUTABLE==statstat..S_IXUSRS_IXUSR||statstat..S_IXGRPS_IXGRP||statstat..S_IXOTHS_IXOTHexecutableModeexecutableMode==STAT_EVERYONE_EXECUTABLESTAT_EVERYONE_EXECUTABLEnewStatenewState==curStatecurState..st_modest_mode||executableModeexecutableModeosos..chmodchmod((someFilesomeFile,,newStatenewState))

效果:

之前: -rw-r--r--

之后: -rwxr-xr-x

给usergroupother都加上 x的可执⾏权限

详⻅:

【已解决】Python中给Mac中⽂件加上可执⾏权限

判断是否是⽂件对象

importimportsyssys

defdefisFileObjectisFileObject((fileObjfileObj))::""""checkisfilelikeobjectornot"""""""checkisfilelikeobjectornot"""ififsyssys..version_infoversion_info[[00]]====22::returnreturnisinstanceisinstance((fileObjfileObj,,filefile))elseelse::#forpython3:#forpython3:#hasread()methodfor:#hasread()methodfor:#io.IOBase#io.IOBase#io.BytesIO#io.BytesIO#io.StringIO#io.StringIO#io.RawIOBase#io.RawIOBasereturnreturnhasattrhasattr((fileObjfileObj,,'read''read'))

计算当前⽂件名,如果重名,则位数加1

importimportososimportimportrere

defdeffindNextNumberFilenamefindNextNumberFilename((curFilenamecurFilename))::"""Findthenextavailablefilenamefromcurrentname"""Findthenextavailablefilenamefromcurrentname

Args:Args:curFilename(str):currentfilenamecurFilename(str):currentfilename

⽂件

26

Page 27: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

Returns:Returns:nextavailable(notexisted)filenamenextavailable(notexisted)filenameRaises:Raises:Examples:Examples:(1)'crifanLib/demo/input/image/20201219_172616_drawRect_40x40.jpg'(1)'crifanLib/demo/input/image/20201219_172616_drawRect_40x40.jpg'notexist->'crifanLib/demo/input/image/20201219_172616_drawRect_40x40.jpg'notexist->'crifanLib/demo/input/image/20201219_172616_drawRect_40x40.jpg'(2)'crifanLib/demo/input/image/20191219_172616_drawRect_40x40.jpg'(2)'crifanLib/demo/input/image/20191219_172616_drawRect_40x40.jpg'exsit->nextuntilnotexist'crifanLib/demo/input/image/20191219_172616_drawexsit->nextuntilnotexist'crifanLib/demo/input/image/20191219_172616_drawRect_40x40_3.jpg'Rect_40x40_3.jpg'""""""newFilenamenewFilename==curFilenamecurFilename

newPathRootPartnewPathRootPart,,pointSuffixpointSuffix==osos..pathpath..splitextsplitext((newFilenamenewFilename))#'crifanLib/demo/input/image/20191219_172616_drawRect_40x40_1'#'crifanLib/demo/input/image/20191219_172616_drawRect_40x40_1'filenamePrefixfilenamePrefix==newPathRootPartnewPathRootPartwhilewhileosos..pathpath..existsexists((newFilenamenewFilename))::newTailNumberIntnewTailNumberInt==11foundTailNumberfoundTailNumber==rere..searchsearch(("^(?P<filenamePrefix>.+)_(?P<tailNumber>\d+)$""^(?P<filenamePrefix>.+)_(?P<tailNumber>\d+)$",,newPatnewPathRootParthRootPart))ififfoundTailNumberfoundTailNumber::tailNumberStrtailNumberStr==foundTailNumberfoundTailNumber..groupgroup(("tailNumber""tailNumber"))#'1'#'1'tailNumberInttailNumberInt==intint((tailNumberStrtailNumberStr))newTailNumberIntnewTailNumberInt==tailNumberInttailNumberInt++11#2#2filenamePrefixfilenamePrefix==foundTailNumberfoundTailNumber..groupgroup(("filenamePrefix""filenamePrefix"))#'crifanLib/demo/inp#'crifanLib/demo/input/image/20191219_172616_drawRect_40x40'ut/image/20191219_172616_drawRect_40x40'#existedpreviouslysaved,changetonewname#existedpreviouslysaved,changetonewnamenewPathRootPartnewPathRootPart=="%s_%s""%s_%s"%%((filenamePrefixfilenamePrefix,,newTailNumberIntnewTailNumberInt))#'crifanLib/demo/input/image/20191219_172616_drawRect_40x40_2'#'crifanLib/demo/input/image/20191219_172616_drawRect_40x40_2'newFilenamenewFilename==newPathRootPartnewPathRootPart++pointSuffixpointSuffix#'crifanLib/demo/input/image/20191219_172616_drawRect_40x40_2.jpg'#'crifanLib/demo/input/image/20191219_172616_drawRect_40x40_2.jpg'

returnreturnnewFilenamenewFilename

调⽤:

notExistFilenotExistFile=="crifanLib/demo/input/image/some_not_exist_filename.jpg""crifanLib/demo/input/image/some_not_exist_filename.jpg"nextFilenamenextFilename==findNextNumberFilenamefindNextNumberFilename((notExistFilenotExistFile))printprint(("notExistFile=%s->nextFilename=%s""notExistFile=%s->nextFilename=%s"%%((notExistFilenotExistFile,,nextFilenamenextFilename))))#notExistFile=crifanLib/demo/input/image/some_not_exist_filename.jpg->nextFilename=cr#notExistFile=crifanLib/demo/input/image/some_not_exist_filename.jpg->nextFilename=crifanLib/demo/input/image/some_not_exist_filename.jpgifanLib/demo/input/image/some_not_exist_filename.jpg

realExistFilerealExistFile=="crifanLib/demo/input/image/20191219_172616_drawRect_40x40.jpg""crifanLib/demo/input/image/20191219_172616_drawRect_40x40.jpg"nextUntilNotExistFilenamenextUntilNotExistFilename==findNextNumberFilenamefindNextNumberFilename((realExistFilerealExistFile))printprint(("realExistFile=%s->nextUntilNotExistFilename=%s""realExistFile=%s->nextUntilNotExistFilename=%s"%%((realExistFilerealExistFile,,nextUntilNotEnextUntilNotExistFilenamexistFilename))))#realExistFile=crifanLib/demo/input/image/20191219_172616_drawRect_40x40.jpg->nextUnt#realExistFile=crifanLib/demo/input/image/20191219_172616_drawRect_40x40.jpg->nextUntilNotExistFilename=crifanLib/demo/input/image/20191219_172616_drawRect_40x40_2.jpgilNotExistFilename=crifanLib/demo/input/image/20191219_172616_drawRect_40x40_2.jpg

从⽂件名后缀推断出MIME类型

⽤库:

⽂件

27

Page 28: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

mimeGitHub

https://github.com/liluo/mime

安装mime:

pippipinstallinstallmimemime

代码:

importimportmimemime

fileMimeTypefileMimeType==mimemime..TypesTypes..ofof((curAudioFullFilenamecurAudioFullFilename))[[00]]..content_typecontent_type

输⼊⽂件: 'LotsofHearts.mp3'

输出信息: 'audio/mpeg'

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

⽂件

28

Page 29: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

⽂件夹=⽂件路径

新建⽂件夹

对于: python3.2+

importimportosos

defdefcreateFoldercreateFolder((folderFullPathfolderFullPath))::""""""createfolder,evenifalreadyexistedcreatefolder,evenifalreadyexistedNote:forPython3.2+Note:forPython3.2+""""""osos..makedirsmakedirs((folderFullPathfolderFullPath,,exist_okexist_ok==TrueTrue))#print("Createdfolder:%s"%folderFullPath)#print("Createdfolder:%s"%folderFullPath)

或:

对于: python3.5+

importimportpathlibpathlibpathlibpathlib..PathPath(('/my/directory''/my/directory'))..mkdirmkdir((parentsparents==TrueTrue,,exist_okexist_ok==TrueTrue))

批量删除⾮空⽂件夹

importimportshutilshutil

ififosos..pathpath..existsexists((folderToDeletefolderToDelete))::shutilshutil..rmtreermtree((folderToDeletefolderToDelete))

注意:

删除之前要先⽤ os.path.exists判断是⾮存在该⽬录

如果不存在就去删除,则会报错: OSError:[Errno2]Nosuchfileordirectory

os.path路径处理

#!/usr/bin/python#!/usr/bin/python#-*-coding:utf-8-*-#-*-coding:utf-8-*-#Author:CrifanLi#Author:CrifanLi#Update:20191219#Update:20191219#Function:Demoos.pathcommonusedfunctions#Function:Demoos.pathcommonusedfunctions

importimportosos

⽂件夹

29

Page 30: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

defdefosPathDemoosPathDemo(())::currentSystemInfocurrentSystemInfo==osos..unameuname(())printprint(("currentSystemInfo=%s""currentSystemInfo=%s"%%((currentSystemInfocurrentSystemInfo,,))))#currentSystemInfo=posix.uname_result(sysname='Darwin',nodename='xxx',release='18.7#currentSystemInfo=posix.uname_result(sysname='Darwin',nodename='xxx',release='18.7.0',version='DarwinKernelVersion18.7.0:SatOct1200:02:19PDT2019;root:xnu-4903.27.0',version='DarwinKernelVersion18.7.0:SatOct1200:02:19PDT2019;root:xnu-4903.278.12~1/RELEASE_X86_64',machine='x86_64')8.12~1/RELEASE_X86_64',machine='x86_64')

pathSeparatorInCurrentOSpathSeparatorInCurrentOS==osos..pathpath..sepsepprintprint(("pathSeparatorInCurrentOS=%s""pathSeparatorInCurrentOS=%s"%%pathSeparatorInCurrentOSpathSeparatorInCurrentOS))#pathSeparatorInCurrentOS=/#pathSeparatorInCurrentOS=/

fullFilePathfullFilePath=="/Users/limao/dev/crifan/python/notEnoughUnpack/Snip20191212_113.png""/Users/limao/dev/crifan/python/notEnoughUnpack/Snip20191212_113.png"printprint(("fullFilePath=%s""fullFilePath=%s"%%fullFilePathfullFilePath))#fullFilePath=/Users/limao/dev/crifan/python/notEnoughUnpack/Snip20191212_113.png#fullFilePath=/Users/limao/dev/crifan/python/notEnoughUnpack/Snip20191212_113.png

dirnamedirname==osos..pathpath..dirnamedirname((fullFilePathfullFilePath))printprint(("dirname=%s""dirname=%s"%%dirnamedirname))#dirname=/Users/limao/dev/crifan/python/notEnoughUnpack#dirname=/Users/limao/dev/crifan/python/notEnoughUnpackbasenamebasename==osos..pathpath..basenamebasename((fullFilePathfullFilePath))printprint(("basename=%s""basename=%s"%%basenamebasename))#basename=Snip20191212_113.png#basename=Snip20191212_113.pngjoinedFullPathjoinedFullPath==osos..pathpath..joinjoin((dirnamedirname,,basenamebasename))printprint(("joinedFullPath=%s""joinedFullPath=%s"%%joinedFullPathjoinedFullPath))#joinedFullPath=/Users/limao/dev/crifan/python/notEnoughUnpack/Snip20191212_113.png#joinedFullPath=/Users/limao/dev/crifan/python/notEnoughUnpack/Snip20191212_113.pngisSameisSame==((fullFilePathfullFilePath====joinedFullPathjoinedFullPath))printprint(("isSame=%s""isSame=%s"%%isSameisSame))#isSame=True#isSame=True

rootroot,,pointSuffixpointSuffix==osos..pathpath..splitextsplitext((fullFilePathfullFilePath))printprint(("root=%s,pointSuffix=%s""root=%s,pointSuffix=%s"%%((rootroot,,pointSuffixpointSuffix))))#root=/Users/limao/dev/crifan/python/notEnoughUnpack/Snip20191212_113,pointSuffix=.p#root=/Users/limao/dev/crifan/python/notEnoughUnpack/Snip20191212_113,pointSuffix=.pngngheadhead,,tailtail==osos..pathpath..splitsplit((fullFilePathfullFilePath))printprint(("head=%s,tail=%s""head=%s,tail=%s"%%((headhead,,tailtail))))#head=/Users/limao/dev/crifan/python/notEnoughUnpack,tail=Snip20191212_113.png#head=/Users/limao/dev/crifan/python/notEnoughUnpack,tail=Snip20191212_113.pngdrivedrive,,tailtail==osos..pathpath..splitdrivesplitdrive((fullFilePathfullFilePath))printprint(("drive=%s,tail=%s""drive=%s,tail=%s"%%((drivedrive,,tailtail))))#drive=,tail=/Users/limao/dev/crifan/python/notEnoughUnpack/Snip20191212_113.png#drive=,tail=/Users/limao/dev/crifan/python/notEnoughUnpack/Snip20191212_113.png

curPathcurPath==osos..getcwdgetcwd(())printprint(("curPath=%s""curPath=%s"%%curPathcurPath))#curPath=/Users/limao/dev/crifan/python#curPath=/Users/limao/dev/crifan/pythonrelativePathrelativePath==osos..pathpath..relpathrelpath((fullFilePathfullFilePath))printprint(("relativePath=%s""relativePath=%s"%%relativePathrelativePath))#relativePath=notEnoughUnpack/Snip20191212_113.png#relativePath=notEnoughUnpack/Snip20191212_113.png

isFileisFile==osos..pathpath..isfileisfile((fullFilePathfullFilePath))printprint(("isFile=%s""isFile=%s"%%isFileisFile))#isFile=True#isFile=TrueisDirectoryisDirectory==osos..pathpath..isdirisdir((fullFilePathfullFilePath))printprint(("isDirectory=%s""isDirectory=%s"%%isDirectoryisDirectory))#isDirectory=False#isDirectory=False

⽂件夹

30

Page 31: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

fileSizefileSize==osos..pathpath..getsizegetsize((fullFilePathfullFilePath))printprint(("fileSize=%s""fileSize=%s"%%fileSizefileSize))#fileSize=368810#fileSize=368810

isFileOrFolderRealExistisFileOrFolderRealExist==osos..pathpath..existsexists((fullFilePathfullFilePath))printprint(("isFileOrFolderRealExist=%s""isFileOrFolderRealExist=%s"%%isFileOrFolderRealExistisFileOrFolderRealExist))#isFileOrFolderRealExist=True#isFileOrFolderRealExist=True

ifif__name____name__===="__main__""__main__"::osPathDemoosPathDemo(())

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

⽂件夹

31

Page 32: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

多媒体

详⻅:

https://github.com/crifan/crifanLibPython/blob/master/crifanLib/crifanMultimedia.pyhttps://github.com/crifan/crifanLibPython/blob/master/crifanLib/demo/crifanMultimediaDemo.py

此处整理多媒体相关的常⽤Python代码段,主要包含如下内容:

图⽚=图像

⾳频

视频

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

多媒体

32

Page 33: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

图像

Python中图像处理⽤的最多是: Pillow

下⾯图像处理处理的代码,基本上都是⽤ Pillow实现的。

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

图像

33

Page 34: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

Pillow

Pillow继承⾃: PIL

PIL= PythonImagingLibrary官⽹资料:

ImageModule—Pillow(PILFork)7.0.0documentationImageModule—Pillow(PILFork)3.1.2documentation

从⼆进制⽣成Image

ififisinstanceisinstance((inputImageinputImage,,bytesbytes))::openableImageopenableImage==ioio..BytesIOBytesIO((inputImageinputImage))curPillowImagecurPillowImage==ImageImage..openopen((openableImageopenableImage))

pillow变量是:

#<PIL.PngImagePlugin.PngImageFileimagemode=RGBAsize=3543x3543at0x1065F7A20>#<PIL.PngImagePlugin.PngImageFileimagemode=RGBAsize=3543x3543at0x1065F7A20>#<PIL.JpegImagePlugin.JpegImageFileimagemode=RGBsize=1080x1920at0x1026D7278>#<PIL.JpegImagePlugin.JpegImageFileimagemode=RGBsize=1080x1920at0x1026D7278>

详⻅:

【已解决】Python如何从⼆进制数据中⽣成Pillow的Image【已解决】Python的Pillow如何从⼆进制数据中读取图像数据

从Pillow的Image获取⼆进制数据

importimportioio

imageIOimageIO==ioio..BytesIOBytesIO(())curImgcurImg..savesave((imageIOimageIO,,curImgcurImg..formatformat))imgBytesimgBytes==imageIOimageIO..getvaluegetvalue(())

详⻅:

【已解决】Python的Pillow如何返回图像的⼆进制数据

缩放图⽚

importimportioiofromfromPILPILimportimportImageImage,,ImageDrawImageDraw

defdefresizeImageresizeImage((inputImageinputImage,,

图像

34

Page 35: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

newSizenewSize,,resampleresample==ImageImage..BICUBICBICUBIC,,#Image.LANCZOS,#Image.LANCZOS,outputFormatoutputFormat==NoneNone,,outputImageFileoutputImageFile==NoneNone))::""""""resizeinputimageresizeinputimageresizenormallymeansbecomesmaller,reducesizeresizenormallymeansbecomesmaller,reducesize:paraminputImage:imagefileobject(fp)/filename/binarybytes:paraminputImage:imagefileobject(fp)/filename/binarybytes:paramnewSize:(width,height):paramnewSize:(width,height):paramresample:PIL.Image.NEAREST,PIL.Image.BILINEAR,PIL.Image.BICUBIC,orPIL.Imag:paramresample:PIL.Image.NEAREST,PIL.Image.BILINEAR,PIL.Image.BICUBIC,orPIL.Image.LANCZOSe.LANCZOShttps://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.thumbhttps://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.thumbnailnail:paramoutputFormat:PNG/JPEG/BMP/GIF/TIFF/WebP/...,morerefer::paramoutputFormat:PNG/JPEG/BMP/GIF/TIFF/WebP/...,morerefer:https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.htmlhttps://pillow.readthedocs.io/en/stable/handbook/image-file-formats.htmlifinputimageisfilenamewithsuffix,canomitthis->willinferfromfilenameifinputimageisfilenamewithsuffix,canomitthis->willinferfromfilenamesuffixsuffix:paramoutputImageFile:outputimagefilefilename:paramoutputImageFile:outputimagefilefilename:return::return:inputimagefilefilename:outputresizedimagetooutputImageFileinputimagefilefilename:outputresizedimagetooutputImageFileinputimagebinarybytes:resizedimagebinarybytesinputimagebinarybytes:resizedimagebinarybytes""""""openableImageopenableImage==NoneNoneififisinstanceisinstance((inputImageinputImage,,strstr))::openableImageopenableImage==inputImageinputImageelifelifisFileObjectisFileObject((inputImageinputImage))::openableImageopenableImage==inputImageinputImageelifelifisinstanceisinstance((inputImageinputImage,,bytesbytes))::inputImageLeninputImageLen==lenlen((inputImageinputImage))openableImageopenableImage==ioio..BytesIOBytesIO((inputImageinputImage))

imageFileimageFile==ImageImage..openopen((openableImageopenableImage))#<PIL.PngImagePlugin.PngImageFileimagemode=RG#<PIL.PngImagePlugin.PngImageFileimagemode=RGBAsize=3543x3543at0x1065F7A20>BAsize=3543x3543at0x1065F7A20>imageFileimageFile..thumbnailthumbnail((newSizenewSize,,resampleresample))ififoutputImageFileoutputImageFile::#savetofile#savetofileimageFileimageFile..savesave((outputImageFileoutputImageFile))imageFileimageFile..closeclose(())elseelse::#saveandreturnbinarybyte#saveandreturnbinarybyteimageOutputimageOutput==ioio..BytesIOBytesIO(())#imageFile.save(imageOutput)#imageFile.save(imageOutput)outputImageFormatoutputImageFormat==NoneNoneififoutputFormatoutputFormat::outputImageFormatoutputImageFormat==outputFormatoutputFormatelifelifimageFileimageFile..formatformat::outputImageFormatoutputImageFormat==imageFileimageFile..formatformatimageFileimageFile..savesave((imageOutputimageOutput,,outputImageFormatoutputImageFormat))imageFileimageFile..closeclose(())compressedImageBytescompressedImageBytes==imageOutputimageOutput..getvaluegetvalue(())compressedImageLencompressedImageLen==lenlen((compressedImageBytescompressedImageBytes))compressRatiocompressRatio==floatfloat((compressedImageLencompressedImageLen))//floatfloat((inputImageLeninputImageLen))

图像

35

Page 36: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

printprint(("%s->%s,resizeratio:%d%%""%s->%s,resizeratio:%d%%"%%((inputImageLeninputImageLen,,compressedImageLencompressedImageLen,,intint((comcompressRatiopressRatio**100100))))))returnreturncompressedImageBytescompressedImageBytes

调⽤:

importimportsyssysimportimportososcurFoldercurFolder==osos..pathpath..abspathabspath((__file____file__))parentFolderparentFolder==osos..pathpath..dirnamedirname((curFoldercurFolder))parentParentFolderparentParentFolder==osos..pathpath..dirnamedirname((parentFolderparentFolder))parentParentParentFolderparentParentParentFolder==osos..pathpath..dirnamedirname((parentParentFolderparentParentFolder))syssys..pathpath..appendappend((curFoldercurFolder))syssys..pathpath..appendappend((parentFolderparentFolder))syssys..pathpath..appendappend((parentParentFolderparentParentFolder))syssys..pathpath..appendappend((parentParentParentFolderparentParentParentFolder))

importimportdatetimedatetimefromfromcrifanMultimediacrifanMultimediaimportimportresizeImageresizeImage

defdeftestFilenametestFilename(())::imageFilenameimageFilename=="/Users/crifan/dev/tmp/python/resize_image_demo/hotday.png""/Users/crifan/dev/tmp/python/resize_image_demo/hotday.png"outputImageFilenameoutputImageFilename=="/Users/crifan/dev/tmp/python/resize_image_demo/hotday_300x300.pn"/Users/crifan/dev/tmp/python/resize_image_demo/hotday_300x300.png"g"printprint(("imageFilename=%s""imageFilename=%s"%%imageFilenameimageFilename))beforeTimebeforeTime==datetimedatetime..datetimedatetime..nownow(())resizeImageresizeImage((imageFilenameimageFilename,,((300300,,300300)),,outputImageFileoutputImageFile==outputImageFilenameoutputImageFilename))afterTimeafterTime==datetimedatetime..datetimedatetime..nownow(())printprint(("procesTime:%s""procesTime:%s"%%((afterTimeafterTime--beforeTimebeforeTime))))

outputImageFilenameoutputImageFilename=="/Users/crifan/dev/tmp/python/resize_image_demo/hotday_800x800.pn"/Users/crifan/dev/tmp/python/resize_image_demo/hotday_800x800.png"g"beforeTimebeforeTime==datetimedatetime..datetimedatetime..nownow(())resizeImageresizeImage((imageFilenameimageFilename,,((800800,,800800)),,outputImageFileoutputImageFile==outputImageFilenameoutputImageFilename))afterTimeafterTime==datetimedatetime..datetimedatetime..nownow(())printprint(("procesTime:%s""procesTime:%s"%%((afterTimeafterTime--beforeTimebeforeTime))))

defdeftestFileObjecttestFileObject(())::imageFilenameimageFilename=="/Users/crifan/dev/tmp/python/resize_image_demo/hotday.png""/Users/crifan/dev/tmp/python/resize_image_demo/hotday.png"imageFileObjimageFileObj==openopen((imageFilenameimageFilename,,"rb""rb"))outputImageFilenameoutputImageFilename=="/Users/crifan/dev/tmp/python/resize_image_demo/hotday_600x600.pn"/Users/crifan/dev/tmp/python/resize_image_demo/hotday_600x600.png"g"beforeTimebeforeTime==datetimedatetime..datetimedatetime..nownow(())resizeImageresizeImage((imageFileObjimageFileObj,,((600600,,600600)),,outputImageFileoutputImageFile==outputImageFilenameoutputImageFilename))afterTimeafterTime==datetimedatetime..datetimedatetime..nownow(())printprint(("procesTime:%s""procesTime:%s"%%((afterTimeafterTime--beforeTimebeforeTime))))

defdeftestBinaryBytestestBinaryBytes(())::imageFilenameimageFilename=="/Users/crifan/dev/tmp/python/resize_image_demo/taketomato.png""/Users/crifan/dev/tmp/python/resize_image_demo/taketomato.png"imageFileObjimageFileObj==openopen((imageFilenameimageFilename,,"rb""rb"))imageBytesimageBytes==imageFileObjimageFileObj..readread(())#returnbinarybytes#returnbinarybytes

图像

36

Page 37: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

beforeTimebeforeTime==datetimedatetime..datetimedatetime..nownow(())resizedImageBytesresizedImageBytes==resizeImageresizeImage((imageBytesimageBytes,,((800800,,800800))))afterTimeafterTime==datetimedatetime..datetimedatetime..nownow(())printprint(("procesTime:%s""procesTime:%s"%%((afterTimeafterTime--beforeTimebeforeTime))))printprint(("len(resizedImageBytes)=%s""len(resizedImageBytes)=%s"%%lenlen((resizedImageBytesresizedImageBytes))))

#savetofile#savetofileoutputImageFilenameoutputImageFilename=="/Users/crifan/dev/tmp/python/resize_image_demo/hotday_750x750.pn"/Users/crifan/dev/tmp/python/resize_image_demo/hotday_750x750.png"g"beforeTimebeforeTime==datetimedatetime..datetimedatetime..nownow(())resizeImageresizeImage((imageBytesimageBytes,,((750750,,750750)),,outputImageFileoutputImageFile==outputImageFilenameoutputImageFilename))afterTimeafterTime==datetimedatetime..datetimedatetime..nownow(())printprint(("procesTime:%s""procesTime:%s"%%((afterTimeafterTime--beforeTimebeforeTime))))

imageFileObjimageFileObj..closeclose(())

defdefdemoResizeImagedemoResizeImage(())::testFilenametestFilename(())testFileObjecttestFileObject(())testBinaryBytestestBinaryBytes(())

ifif__name____name__===="__main__""__main__"::demoResizeImagedemoResizeImage(())

#imageFilename=/Users/crifan/dev/tmp/python/resize_image_demo/hotday.png#imageFilename=/Users/crifan/dev/tmp/python/resize_image_demo/hotday.png#procesTime:0:00:00.619377#procesTime:0:00:00.619377#procesTime:0:00:00.745228#procesTime:0:00:00.745228#procesTime:0:00:00.606060#procesTime:0:00:00.606060#1146667->753258,resizeratio:65%#1146667->753258,resizeratio:65%#procesTime:0:00:00.773289#procesTime:0:00:00.773289#len(resizedImageBytes)=753258#len(resizedImageBytes)=753258#procesTime:0:00:00.738237#procesTime:0:00:00.738237

给图⽚画元素所属区域的边框,且带⾃动保存加了框后的图⽚

fromfromPILPILimportimportImageImagefromfromPILPILimportimportImageDrawImageDraw

defdefimageDrawRectangleimageDrawRectangle((inputImgOrImgPathinputImgOrImgPath,,rectLocationrectLocation,,outlineColoroutlineColor=="green""green",,outlineWidthoutlineWidth==00,,isShowisShow==FalseFalse,,isAutoSaveisAutoSave==TrueTrue,,saveTailsaveTail=="_drawRect_%wx%h""_drawRect_%wx%h",,isDrawClickedPosCircleisDrawClickedPosCircle==TrueTrue,,clickedPosclickedPos==NoneNone,,))::"""Drawarectangleforimage(andasmallcircle),andshowit,"""Drawarectangleforimage(andasmallcircle),andshowit,

Args:Args:

图像

37

Page 38: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

inputImgOrImgPath(Image/str):apillow(PIL)ImageinstanceorimagefilepathinputImgOrImgPath(Image/str):apillow(PIL)ImageinstanceorimagefilepathrectLocation(tuple/list/Rect):therectanglelocation,(x,y,width,height)rectLocation(tuple/list/Rect):therectanglelocation,(x,y,width,height)outlineColor(str):ColornameoutlineColor(str):ColornameoutlineWidth(int):rectangleoutlinewidthoutlineWidth(int):rectangleoutlinewidthisShow(bool):Truetocallimage.show()fordebugisShow(bool):Truetocallimage.show()fordebugisAutoSave(bool):TruetoautosavetheimagefilewithdrawedrectangleisAutoSave(bool):TruetoautosavetheimagefilewithdrawedrectanglesaveTail(str):savefilenametailpart.supportformat%x/%y/%w/%huseonlywhenisaveTail(str):savefilenametailpart.supportformat%x/%y/%w/%huseonlywhenisAutoSave=TruesAutoSave=TrueclickedPos(tuple):x,yofclickedpostion;defaultNone;ifNone,usethecenterclickedPos(tuple):x,yofclickedpostion;defaultNone;ifNone,usethecenterpointpointisDrawClickedPosCircle(bool):drawsmallcircleinclickedpointisDrawClickedPosCircle(bool):drawsmallcircleinclickedpointReturns:Returns:modifiedimagemodifiedimageRaises:Raises:""""""inputImginputImg==inputImgOrImgPathinputImgOrImgPathififisinstanceisinstance((inputImgOrImgPathinputImgOrImgPath,,strstr))::inputImginputImg==ImageImage..openopen((inputImgOrImgPathinputImgOrImgPath))drawdraw==ImageDrawImageDraw..DrawDraw((inputImginputImg))

isRectObjisRectObj==FalseFalsehasXhasX==hasattrhasattr((rectLocationrectLocation,,"x""x"))hasYhasY==hasattrhasattr((rectLocationrectLocation,,"y""y"))hasWidthhasWidth==hasattrhasattr((rectLocationrectLocation,,"width""width"))hasHeighthasHeight==hasattrhasattr((rectLocationrectLocation,,"height""height"))isRectObjisRectObj==hasXhasXandandhasYhasYandandhasWidthhasWidthandandhasHeighthasHeightififisinstanceisinstance((rectLocationrectLocation,,tupletuple))::xx,,yy,,ww,,hh==rectLocationrectLocationififisinstanceisinstance((rectLocationrectLocation,,listlist))::xx==rectLocationrectLocation[[00]]yy==rectLocationrectLocation[[11]]ww==rectLocationrectLocation[[22]]hh==rectLocationrectLocation[[33]]elifelifisRectObjisRectObj::xx==rectLocationrectLocation..xxyy==rectLocationrectLocation..yyww==rectLocationrectLocation..widthwidthhh==rectLocationrectLocation..heightheight

ww==intint((ww))hh==intint((hh))x0x0==xxy0y0==yyx1x1==x0x0++wwy1y1==y0y0++hhdrawdraw..rectanglerectangle(([[x0x0,,y0y0,,x1x1,,y1y1]],,#fill="yellow",#fill="yellow",#outline="yellow",#outline="yellow",outlineoutline==outlineColoroutlineColor,,widthwidth==outlineWidthoutlineWidth,,))

图像

38

Page 39: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

ififisDrawClickedPosCircleisDrawClickedPosCircle::#radius=3#radius=3#radius=2#radius=2radiusradius==44#circleOutline="yellow"#circleOutline="yellow"circleOutlinecircleOutline=="red""red"circleLineWidthIntcircleLineWidthInt==11#circleLineWidthInt=3#circleLineWidthInt=3

ififclickedPosclickedPos::clickedXclickedX,,clickedYclickedY==clickedPosclickedPoselseelse::clickedXclickedX==xx++ww//22clickedYclickedY==yy++hh//22startPointIntstartPointInt==((intint((clickedXclickedX--radiusradius)),,intint((clickedYclickedY--radiusradius))))endPointIntendPointInt==((intint((clickedXclickedX++radiusradius)),,intint((clickedYclickedY++radiusradius))))drawdraw..ellipseellipse(([[startPointIntstartPointInt,,endPointIntendPointInt]],,outlineoutline==circleOutlinecircleOutline,,widthwidth==circleLinecircleLineWidthIntWidthInt))

ififisShowisShow::inputImginputImg..showshow(())

ififisAutoSaveisAutoSave::saveTailsaveTail==saveTailsaveTail..replacereplace(("%x""%x",,strstr((xx))))saveTailsaveTail==saveTailsaveTail..replacereplace(("%y""%y",,strstr((yy))))saveTailsaveTail==saveTailsaveTail..replacereplace(("%w""%w",,strstr((ww))))saveTailsaveTail==saveTailsaveTail..replacereplace(("%h""%h",,strstr((hh))))

inputImgPathinputImgPath==NoneNoneififisinstanceisinstance((inputImgOrImgPathinputImgOrImgPath,,strstr))::inputImgPathinputImgPath==strstr((inputImgOrImgPathinputImgOrImgPath))elifelifinputImginputImg..filenamefilename::inputImgPathinputImgPath==strstr((inputImginputImg..filenamefilename))

ififinputImgPathinputImgPath::imgFolderAndNameimgFolderAndName,,pointSuffixpointSuffix==osos..pathpath..splitextsplitext((inputImgPathinputImgPath))imgFolderAndNameimgFolderAndName==imgFolderAndNameimgFolderAndName++saveTailsaveTailnewImgPathnewImgPath==imgFolderAndNameimgFolderAndName++pointSuffixpointSuffixnewImgPathnewImgPath==findNextNumberFilenamefindNextNumberFilename((newImgPathnewImgPath))elseelse::curDatetimeStrcurDatetimeStr==getCurDatetimeStrgetCurDatetimeStr(())#'20191219_143400'#'20191219_143400'suffixsuffix==strstr((inputImginputImg..formatformat))..lowerlower(())#'jpeg'#'jpeg'newImgFilenamenewImgFilename=="%s%s.%s""%s%s.%s"%%((curDatetimeStrcurDatetimeStr,,saveTailsaveTail,,suffixsuffix))imgPathRootimgPathRoot==osos..getcwdgetcwd(())newImgPathnewImgPath==osos..pathpath..joinjoin((imgPathRootimgPathRoot,,newImgFilenamenewImgFilename))

inputImginputImg..savesave((newImgPathnewImgPath))

returnreturninputImginputImg

说明:

相关函数,详⻅:findNextNumberFilename,或者⼲脆去掉这个逻辑即可。

图像

39

Page 40: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

调⽤:

curBoundListcurBoundList==selfself..get_ElementBoundsget_ElementBounds((eachElementeachElement))curWidthcurWidth==curBoundListcurBoundList[[22]]--curBoundListcurBoundList[[00]]curHeightcurHeight==curBoundListcurBoundList[[33]]--curBoundListcurBoundList[[11]]curRectcurRect==[[curBoundListcurBoundList[[00]],,curBoundListcurBoundList[[11]],,curWidthcurWidth,,curHeightcurHeight]]curImgcurImg==CommonUtilsCommonUtils..imageDrawRectangleimageDrawRectangle((curImgcurImg,,curRectcurRect,,isShowisShow==TrueTrue,,saveTailsaveTail=="_rect_%x|%"_rect_%x|%y|%w|%h"y|%w|%h",,isDrawClickedPosCircleisDrawClickedPosCircle==FalseFalse))

或:

curTimeStrcurTimeStr==CommonUtilsCommonUtils..getCurDatetimeStrgetCurDatetimeStr(("%H%M%S""%H%M%S"))curSaveTalcurSaveTal=="_rect_{}_%x|%y|%w|%h""_rect_{}_%x|%y|%w|%h"..formatformat((curTimeStrcurTimeStr))curImgcurImg==CommonUtilsCommonUtils..imageDrawRectangleimageDrawRectangle((imgPathimgPath,,curRectcurRect,,isShowisShow==TrueTrue,,saveTailsaveTail==curSaveTalcurSaveTal,,isDrawClickedPosCircleisDrawClickedPosCircle==FalseFalse))

效果:

(1)给原图加上单个元素所属边框

图像

40

Page 41: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

(2)多次循环后,给同⼀张图中多个元素加上边框后

图像

41

Page 42: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

其他调⽤:

imageDrawRectangleimageDrawRectangle((curPillowImgcurPillowImg,,curLocationcurLocation))

imageDrawRectangleimageDrawRectangle((curPillowImgcurPillowImg,,calculatedLocationcalculatedLocation))

curImgcurImg==imageDrawRectangleimageDrawRectangle((imgPathimgPath,,firstMatchLocationfirstMatchLocation,,clickedPosclickedPos==clickedPosclickedPos))

图像

42

Page 43: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

curImgcurImg==imageDrawRectangleimageDrawRectangle((imgPathimgPath,,firstMatchLocationfirstMatchLocation))

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

图像

43

Page 44: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

百度OCR

详⻅:

https://github.com/crifan/crifanLibPython/blob/master/crifanLib/crifanBaiduOcr.py

在做安卓和iOS的移动端⾃动化测试期间,会涉及到从图像中提取⽂字,⽤的是百度OCR。

其中有些通⽤的功能,整理出函数,贴出供参考。

百度OCR初始化

importimportososimportimportrereimportimportbase64base64importimportrequestsrequestsimportimporttimetimeimportimportloggingloggingfromfromcollectionscollectionsimportimportOrderedDictOrderedDictfromfromPILPILimportimportImageImage,,ImageDrawImageDraw

classclassBaiduOCRBaiduOCR(())::#OCR_URL="https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"##OCR_URL="https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"#通⽤⽂字识别通⽤⽂字识别

#OCR_URL="https://aip.baidubce.com/rest/2.0/ocr/v1/general"##OCR_URL="https://aip.baidubce.com/rest/2.0/ocr/v1/general"#通⽤⽂字识别(含通⽤⽂字识别(含

位置信息版)位置信息版)

#OCR_URL="https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"##OCR_URL="https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"#通⽤⽂字识别(⾼通⽤⽂字识别(⾼

精度版)精度版)

OCR_URLOCR_URL=="https://aip.baidubce.com/rest/2.0/ocr/v1/accurate""https://aip.baidubce.com/rest/2.0/ocr/v1/accurate"##通⽤⽂字识别(⾼精通⽤⽂字识别(⾼精

度含位置版)度含位置版)

TOKEN_URLTOKEN_URL=='https://aip.baidubce.com/oauth/2.0/token''https://aip.baidubce.com/oauth/2.0/token'

RESP_ERR_CODE_QPS_LIMIT_REACHEDRESP_ERR_CODE_QPS_LIMIT_REACHED==1818RESP_ERR_TEXT_QPS_LIMIT_REACHEDRESP_ERR_TEXT_QPS_LIMIT_REACHED=="Openapiqpsrequestlimitreached""Openapiqpsrequestlimitreached"

RESP_ERR_CODE_DAILY_LIMIT_REACHEDRESP_ERR_CODE_DAILY_LIMIT_REACHED==1717RESP_ERR_TEXT_DAILY_LIMIT_REACHEDRESP_ERR_TEXT_DAILY_LIMIT_REACHED=="Openapidailyrequestlimitreached""Openapidailyrequestlimitreached"

API_KEYAPI_KEY=='SOxxxxxxxxxxnu''SOxxxxxxxxxxnu'SECRET_KEYSECRET_KEY=='wlxxxxxxxxxxxxxxxxxxxpL''wlxxxxxxxxxxxxxxxxxxxpL'

defdefinitOcrinitOcr((selfself))::selfself..curTokencurToken==selfself..baiduFetchTokenbaiduFetchToken(())

图像

44

Page 45: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

defdefbaiduFetchTokenbaiduFetchToken((selfself))::"""FetchBaidutokenforOCR""""""FetchBaidutokenforOCR"""paramsparams=={{'grant_type''grant_type'::'client_credentials''client_credentials',,'client_id''client_id'::selfself..API_KEYAPI_KEY,,'client_secret''client_secret'::selfself..SECRET_KEYSECRET_KEY}}

respresp==requestsrequests..getget((selfself..TOKEN_URLTOKEN_URL,,paramsparams==paramsparams))respJsonrespJson==respresp..jsonjson(())

respTokenrespToken==""""

ifif(('access_token''access_token'ininrespJsonrespJson..keyskeys(())andand'scope''scope'ininrespJsonrespJson..keyskeys(())))::ififnotnot'brain_all_scope''brain_all_scope'ininrespJsonrespJson[['scope''scope']]..splitsplit((''''))::logginglogging..errorerror(('pleaseensurehaschecktheability''pleaseensurehaschecktheability'))elseelse::respTokenrespToken==respJsonrespJson[['access_token''access_token']]elseelse::logginglogging..errorerror(('pleaseoverwritethecorrectAPI_KEYandSECRET_KEY''pleaseoverwritethecorrectAPI_KEYandSECRET_KEY'))

#'24.8691f3c6dedd0d0d0b30a9dfec604d52.2592000.1578465979.282335-17921535'#'24.8691f3c6dedd0d0d0b30a9dfec604d52.2592000.1578465979.282335-17921535'returnreturnrespTokenrespToken

百度OCR图⽚转⽂字

defdefbaiduImageToWordsbaiduImageToWords((selfself,,imageFullPathimageFullPath))::"""DetecttextfromimageusingBaiduOCRapi""""""DetecttextfromimageusingBaiduOCRapi"""

##Note:ifusingun-paid=freebaiduapi,needfollowingwaitsometimetoreduce:q##Note:ifusingun-paid=freebaiduapi,needfollowingwaitsometimetoreduce:qpsrequestlimitpsrequestlimit#time.sleep(0.15)#time.sleep(0.15)

respWordsResutJsonrespWordsResutJson==""""

##读取图⽚⼆进制数据读取图⽚⼆进制数据

imgBinDataimgBinData==readBinDataFromFilereadBinDataFromFile((imageFullPathimageFullPath))encodedImgDataencodedImgData==base64base64..b64encodeb64encode((imgBinDataimgBinData))

paramDictparamDict=={{"access_token""access_token"::selfself..curTokencurToken}}

headerDictheaderDict=={{"Content-Type""Content-Type"::"application/x-www-form-urlencoded""application/x-www-form-urlencoded"

图像

45

Page 46: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

}}

##参数含义:参数含义:http://ai.baidu.com/ai-doc/OCR/vk3h7y58vhttp://ai.baidu.com/ai-doc/OCR/vk3h7y58vdataDictdataDict=={{"image""image"::encodedImgDataencodedImgData,,"recognize_granularity""recognize_granularity"::"small""small",,#"vertexes_location":"true",#"vertexes_location":"true",}}respresp==requestsrequests..postpost((selfself..OCR_URLOCR_URL,,paramsparams==paramDictparamDict,,headersheaders==headerDictheaderDict,,datadata==dataDictdataDict))

respJsonrespJson==respresp..jsonjson(())

logginglogging..debugdebug(("baiduOCR:imgage=%s->respJson=%s""baiduOCR:imgage=%s->respJson=%s",,imageFullPathimageFullPath,,respJsonrespJson))

ifif"error_code""error_code"ininrespJsonrespJson::logginglogging..warningwarning(("respJson=%s""respJson=%s"%%respJsonrespJson))errorCodeerrorCode==respJsonrespJson[["error_code""error_code"]]#{'error_code':17,'error_msg':'Openapidailyrequestlimitreached'}#{'error_code':17,'error_msg':'Openapidailyrequestlimitreached'}#{'error_code':18,'error_msg':'Openapiqpsrequestlimitreached'}#{'error_code':18,'error_msg':'Openapiqpsrequestlimitreached'}#thelimitcountcanfoundfrom#thelimitcountcanfoundfrom##⽂字识别⽂字识别--免费额度免费额度||百度百度AIAI开放平台开放平台

#https://ai.baidu.com/ai-doc/OCR/fk3h7xu7h#https://ai.baidu.com/ai-doc/OCR/fk3h7xu7h#for"#for"通⽤⽂字识别(⾼精度含位置版)通⽤⽂字识别(⾼精度含位置版)"is"50"is"50次次//天天""ififerrorCodeerrorCode====selfself..RESP_ERR_CODE_QPS_LIMIT_REACHEDRESP_ERR_CODE_QPS_LIMIT_REACHED::#waitsometimeandtryagain#waitsometimeandtryagaintimetime..sleepsleep((1.01.0))respresp==requestsrequests..postpost((selfself..OCR_URLOCR_URL,,paramsparams==paramDictparamDict,,headersheaders==headerDictheaderDict,,datadata==dataDictdataDict))respJsonrespJson==respresp..jsonjson(())logginglogging..debugdebug(("baiduOCR:forerrorCode=%s,doagain,imgage=%s->respJson=%s""baiduOCR:forerrorCode=%s,doagain,imgage=%s->respJson=%s",,errorCodeerrorCode,,imageFullPathimageFullPath,,respJsonrespJson))elifeliferrorCodeerrorCode====selfself..RESP_ERR_CODE_DAILY_LIMIT_REACHEDRESP_ERR_CODE_DAILY_LIMIT_REACHED::logginglogging..errorerror(("FailtocontinueusingbaiduOCRapitoday!!!""FailtocontinueusingbaiduOCRapitoday!!!"))respJsonrespJson==NoneNone

""""""{{"log_id":6937531796498618000,"log_id":6937531796498618000,"words_result_num":32,"words_result_num":32,"words_result":["words_result":[{{"chars":["chars":[......""""""ifif"words_result""words_result"ininrespJsonrespJson::respWordsResutJsonrespWordsResutJson==respJsonrespJson

returnreturnrespWordsResutJsonrespWordsResutJson

调⽤:

wordsResultJsonwordsResultJson==selfself..baiduImageToWordsbaiduImageToWords((imgPathimgPath))

图像

46

Page 47: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

respJsonrespJson==selfself..baiduImageToWordsbaiduImageToWords((screenImgPathscreenImgPath))

返回结果举例

安卓游戏暗⿊觉醒⾸充豪礼

图⽚:

返回解析后出 json格式的⽂字信息:

{{"log_id""log_id"::90097707473706400079009770747370640007,,"words_result_num""words_result_num"::1212,,"words_result""words_result"::[[{{"chars""chars"::[[{{"char""char"::""⾸⾸"",,"location""location"::{{"width""width"::9494,,"top""top"::105105,,"left""left"::989989,,"height""height"::158158}}}},,{{"char""char"::""充充"",,"location""location"::{{"width""width"::9494,,"top""top"::105105,,"left""left"::10861086,,"height""height"::158158}}}},,{{"char""char"::""豪豪"",,"location""location"::{{"width""width"::9595,,"top""top"::105105,,"left""left"::11831183,,"height""height"::158158}}}},,{{"char""char"::""礼礼"",,"location""location"::{{"width""width"::7777,,"top""top"::105105,,"left""left"::12811281,,"height""height"::158158}}}}]],,"location""location"::{{"width""width"::370370,,"top""top"::105105,,"left""left"::989989,,"height""height"::158158}},,

图像

47

Page 48: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"words""words"::""⾸充豪礼⾸充豪礼""}},,{{"chars""chars"::[[{{"char""char"::"×""×",,"location""location"::{{"width""width"::3030,,"top""top"::161161,,"left""left"::18871887,,"height""height"::6161}}}}]],,"location""location"::{{"width""width"::6060,,"top""top"::161161,,"left""left"::18871887,,"height""height"::6161}},,"words""words"::"×""×"}},,{{"chars""chars"::[[{{"char""char"::""充充"",,"location""location"::{{"width""width"::4343,,"top""top"::273273,,"left""left"::758758,,"height""height"::7373}}}},,{{"char""char"::""值值"",,"location""location"::{{"width""width"::4343,,"top""top"::273273,,"left""left"::803803,,"height""height"::7373}}}},,{{"char""char"::""元元"",,"location""location"::{{"width""width"::6767,,"top""top"::273273,,"left""left"::912912,,"height""height"::7373}}}},,{{"char""char"::""可可"",,"location""location"::{{"width""width"::4444,,"top""top"::273273,,"left""left"::979979,,"height""height"::7373}}}},,{{"char""char"::""领领"",,"location""location"::{{"width""width"::4343,,"top""top"::273273,,"left""left"::10231023,,"height""height"::7373}}}},,{{"char""char"::""总总"",,"location""location"::{{"width""width"::4444,,"top""top"::273273,,"left""left"::10671067,,"height""height"::7373}}}},,{{"char""char"::""价价"",,"location""location"::{{"width""width"::2323,,"top""top"::273273,,"left""left"::11111111,,"height""height"::7373}}}},,{{"char""char"::""值值"",,"location""location"::{{"width""width"::8989,,"top""top"::273273,,"left""left"::11341134,,"height""height"::7373}}}},,{{"char""char"::"8""8",,"location""location"::{{"width""width"::3636,,"top""top"::273273,,"left""left"::12591259,,"height""height"::7373}}}},,{{"char""char"::"8""8",,"location""location"::{{"width""width"::3636,,"top""top"::273273,,"left""left"::13261326,,"height""height"::7373}}

图像

48

Page 49: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

}},,{{"char""char"::"8""8",,"location""location"::{{"width""width"::3535,,"top""top"::273273,,"left""left"::13711371,,"height""height"::7373}}}},,{{"char""char"::""钻钻"",,"location""location"::{{"width""width"::4343,,"top""top"::273273,,"left""left"::14441444,,"height""height"::7373}}}},,{{"char""char"::""豪豪"",,"location""location"::{{"width""width"::4444,,"top""top"::273273,,"left""left"::15101510,,"height""height"::7373}}}},,{{"char""char"::""华华"",,"location""location"::{{"width""width"::4343,,"top""top"::273273,,"left""left"::15551555,,"height""height"::7373}}}},,{{"char""char"::""⼤⼤"",,"location""location"::{{"width""width"::4343,,"top""top"::273273,,"left""left"::15991599,,"height""height"::7373}}}},,{{"char""char"::""礼礼"",,"location""location"::{{"width""width"::2727,,"top""top"::273273,,"left""left"::16431643,,"height""height"::7373}}}}]],,"location""location"::{{"width""width"::911911,,"top""top"::273273,,"left""left"::758758,,"height""height"::7373}},,"words""words"::""充值元可领总价值充值元可领总价值888888钻豪华⼤礼钻豪华⼤礼""}},,{{"chars""chars"::[[{{"char""char"::""送送"",,"location""location"::{{"width""width"::6565,,"top""top"::369369,,"left""left"::832832,,"height""height"::107107}}}}]],,"location""location"::{{"width""width"::107107,,"top""top"::369369,,"left""left"::832832,,"height""height"::107107}},,"words""words"::""送送""}},,{{"chars""chars"::[[{{"char""char"::""绝绝"",,"location""location"::{{"width""width"::3838,,"top""top"::390390,,"left""left"::974974,,"height""height"::6565}}}},,{{"char""char"::""版版"",,"location""location"::{{"width""width"::3838,,"top""top"::390390,,"left""left"::10321032,,"height""height"::6565}}}},,{{"char""char"::""萌萌"",,"location""location"::{{"width""width"::3838,,"top""top"::390390,,"left""left"::10921092,,"height""height"::6565}}}},,

图像

49

Page 50: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

{{"char""char"::""宠宠"",,"location""location"::{{"width""width"::3838,,"top""top"::390390,,"left""left"::11501150,,"height""height"::6565}}}},,{{"char""char"::""、、"",,"location""location"::{{"width""width"::3131,,"top""top"::390390,,"left""left"::11841184,,"height""height"::6565}}}},,{{"char""char"::""专专"",,"location""location"::{{"width""width"::3939,,"top""top"::390390,,"left""left"::12301230,,"height""height"::6565}}}},,{{"char""char"::""属属"",,"location""location"::{{"width""width"::3838,,"top""top"::390390,,"left""left"::12891289,,"height""height"::6565}}}},,{{"char""char"::""神神"",,"location""location"::{{"width""width"::3838,,"top""top"::390390,,"left""left"::13681368,,"height""height"::6565}}}},,{{"char""char"::""兵兵"",,"location""location"::{{"width""width"::3939,,"top""top"::390390,,"left""left"::14081408,,"height""height"::6565}}}}]],,"location""location"::{{"width""width"::524524,,"top""top"::390390,,"left""left"::934934,,"height""height"::6565}},,"words""words"::""绝版萌宠、专属神兵绝版萌宠、专属神兵""}},,{{"chars""chars"::[[{{"char""char"::""绝绝"",,"location""location"::{{"width""width"::2020,,"top""top"::515515,,"left""left"::378378,,"height""height"::3333}}}}]],,"location""location"::{{"width""width"::3333,,"top""top"::515515,,"left""left"::378378,,"height""height"::3333}},,"words""words"::""绝绝""}},,{{"chars""chars"::[[{{"char""char"::""珍珍"",,"location""location"::{{"width""width"::3333,,"top""top"::516516,,"left""left"::19921992,,"height""height"::4242}}}}]],,"location""location"::{{"width""width"::3333,,"top""top"::516516,,"left""left"::19921992,,"height""height"::4242}},,"words""words"::""珍珍""}},,{{"chars""chars"::[[{{"char""char"::""版版"",,"location""location"::{{"width""width"::2020,,"top""top"::545545,,"left""left"::379379,,"height""height"::3434}}

图像

50

Page 51: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

}}]],,"location""location"::{{"width""width"::3131,,"top""top"::545545,,"left""left"::379379,,"height""height"::3434}},,"words""words"::""版版""}},,{{"chars""chars"::[[{{"char""char"::""额额"",,"location""location"::{{"width""width"::2626,,"top""top"::776776,,"left""left"::12251225,,"height""height"::4444}}}},,{{"char""char"::""外外"",,"location""location"::{{"width""width"::2626,,"top""top"::776776,,"left""left"::12641264,,"height""height"::4444}}}},,{{"char""char"::""礼礼"",,"location""location"::{{"width""width"::2727,,"top""top"::776776,,"left""left"::12911291,,"height""height"::4444}}}},,{{"char""char"::""包包"",,"location""location"::{{"width""width"::2727,,"top""top"::776776,,"left""left"::13171317,,"height""height"::4444}}}}]],,"location""location"::{{"width""width"::125125,,"top""top"::776776,,"left""left"::12251225,,"height""height"::4444}},,"words""words"::""额外礼包额外礼包""}},,{{"chars""chars"::[[{{"char""char"::""⾸⾸"",,"location""location"::{{"width""width"::3838,,"top""top"::830830,,"left""left"::935935,,"height""height"::6464}}}},,{{"char""char"::""充充"",,"location""location"::{{"width""width"::3838,,"top""top"::830830,,"left""left"::994994,,"height""height"::6464}}}},,{{"char""char"::""元元"",,"location""location"::{{"width""width"::3838,,"top""top"::830830,,"left""left"::10921092,,"height""height"::6464}}}},,{{"char""char"::""充充"",,"location""location"::{{"width""width"::3838,,"top""top"::830830,,"left""left"::12861286,,"height""height"::6464}}}},,{{"char""char"::"9""9",,"location""location"::{{"width""width"::3131,,"top""top"::830830,,"left""left"::13391339,,"height""height"::6464}}}},,{{"char""char"::"8""8",,"location""location"::{{"width""width"::3131,,"top""top"::830830,,"left""left"::13771377,,"height""height"::6464}}}},,

图像

51

Page 52: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

{{"char""char"::""元元"",,"location""location"::{{"width""width"::3838,,"top""top"::830830,,"left""left"::14441444,,"height""height"::6464}}}}]],,"location""location"::{{"width""width"::549549,,"top""top"::830830,,"left""left"::935935,,"height""height"::6464}},,"words""words"::""⾸充元充⾸充元充9898元元""}},,{{"chars""chars"::[[{{"char""char"::""战战"",,"location""location"::{{"width""width"::4242,,"top""top"::970970,,"left""left"::373373,,"height""height"::6969}}}},,{{"char""char"::""⽃⽃"",,"location""location"::{{"width""width"::4242,,"top""top"::970970,,"left""left"::437437,,"height""height"::6969}}}},,{{"char""char"::"1""1",,"location""location"::{{"width""width"::3535,,"top""top"::970970,,"left""left"::515515,,"height""height"::6969}}}},,{{"char""char"::"5""5",,"location""location"::{{"width""width"::3535,,"top""top"::970970,,"left""left"::537537,,"height""height"::6969}}}},,{{"char""char"::"0""0",,"location""location"::{{"width""width"::3434,,"top""top"::970970,,"left""left"::580580,,"height""height"::6969}}}},,{{"char""char"::"0""0",,"location""location"::{{"width""width"::3535,,"top""top"::970970,,"left""left"::622622,,"height""height"::6969}}}},,{{"char""char"::"0""0",,"location""location"::{{"width""width"::3434,,"top""top"::970970,,"left""left"::666666,,"height""height"::6969}}}}]],,"location""location"::{{"width""width"::327327,,"top""top"::970970,,"left""left"::373373,,"height""height"::6969}},,"words""words"::""战⽃战⽃15000"15000"}},,{{"chars""chars"::[[{{"char""char"::""战战"",,"location""location"::{{"width""width"::4343,,"top""top"::969969,,"left""left"::16481648,,"height""height"::7373}}}},,{{"char""char"::""⽃⽃"",,"location""location"::{{"width""width"::4343,,"top""top"::969969,,"left""left"::17131713,,"height""height"::7373}}}},,{{

图像

52

Page 53: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"char""char"::"1""1",,"location""location"::{{"width""width"::3636,,"top""top"::969969,,"left""left"::17931793,,"height""height"::7373}}}},,{{"char""char"::"6""6",,"location""location"::{{"width""width"::3636,,"top""top"::969969,,"left""left"::18161816,,"height""height"::7373}}}},,{{"char""char"::"0""0",,"location""location"::{{"width""width"::3535,,"top""top"::969969,,"left""left"::18611861,,"height""height"::7373}}}},,{{"char""char"::"0""0",,"location""location"::{{"width""width"::3636,,"top""top"::969969,,"left""left"::19041904,,"height""height"::7373}}}},,{{"char""char"::"0""0",,"location""location"::{{"width""width"::2929,,"top""top"::969969,,"left""left"::19491949,,"height""height"::7373}}}}]],,"location""location"::{{"width""width"::330330,,"top""top"::969969,,"left""left"::16481648,,"height""height"::7373}},,"words""words"::""战⽃战⽃16000"16000"}}]]}}

其中:

⾸充豪礼

都能完整检测出来:已经是效果很不错了

当然偶尔也会有失误,⽐如偶尔

只解析出部分内容:⾸充豪

或个别字错了:⾸充豪机

本身图⽚上礼也的确很像机作为OCR犯此错误,完全可以理解

安卓游戏暗⿊觉醒公告弹框

图⽚:

图像

53

Page 54: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

返回结果json:

{{"log_id""log_id"::27933917732895504722793391773289550472,,"words_result_num""words_result_num"::2323,,"words_result""words_result"::[[{{"chars""chars"::[[{{"char""char"::""公公"",,"location""location"::{{"width""width"::2828,,"top""top"::125125,,"left""left"::634634,,"height""height"::4848}}}},,{{"char""char"::""告告"",,"location""location"::{{"width""width"::2929,,"top""top"::125125,,"left""left"::691691,,"height""height"::4848}}}}]],,"location""location"::{{"width""width"::9292,,"top""top"::125125,,"left""left"::634634,,"height""height"::4848}},,"words""words"::""公告公告""}},,{{"chars""chars"::[[{{"char""char"::""最最"",,"location""location"::{{"width""width"::2121,,"top""top"::240240,,"left""left"::535535,,"height""height"::3636}}}}]],,"location""location"::{{"width""width"::3333,,"top""top"::240240,,"left""left"::535535,,"height""height"::3636}},,"words""words"::""最最""}},,{{"chars""chars"::[[{{"char""char"::""亲亲"",,"location""location"::{{"width""width"::2626,,"top""top"::233233,,"left""left"::922922,,"height""height"::4242}}}},,

图像

54

Page 55: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

{{"char""char"::""爱爱"",,"location""location"::{{"width""width"::2626,,"top""top"::233233,,"left""left"::959959,,"height""height"::4242}}}},,{{"char""char"::""的的"",,"location""location"::{{"width""width"::2626,,"top""top"::233233,,"left""left"::986986,,"height""height"::4242}}}},,{{"char""char"::""觉觉"",,"location""location"::{{"width""width"::2626,,"top""top"::233233,,"left""left"::10241024,,"height""height"::4242}}}},,{{"char""char"::""醒醒"",,"location""location"::{{"width""width"::2626,,"top""top"::233233,,"left""left"::10631063,,"height""height"::4242}}}},,{{"char""char"::""勇勇"",,"location""location"::{{"width""width"::2626,,"top""top"::233233,,"left""left"::10881088,,"height""height"::4242}}}},,{{"char""char"::""⼠⼠"",,"location""location"::{{"width""width"::2525,,"top""top"::233233,,"left""left"::11271127,,"height""height"::4242}}}},,{{"char""char"::":"":",,"location""location"::{{"width""width"::2121,,"top""top"::233233,,"left""left"::11481148,,"height""height"::4242}}}}]],,"location""location"::{{"width""width"::253253,,"top""top"::233233,,"left""left"::922922,,"height""height"::4242}},,"words""words"::""亲爱的觉醒勇⼠亲爱的觉醒勇⼠:":"}},,{{"chars""chars"::[[{{"char""char"::""新新"",,"location""location"::{{"width""width"::2626,,"top""top"::266266,,"left""left"::535535,,"height""height"::4444}}}},,{{"char""char"::""新新"",,"location""location"::{{"width""width"::2727,,"top""top"::266266,,"left""left"::588588,,"height""height"::4444}}}},,{{"char""char"::""服服"",,"location""location"::{{"width""width"::2626,,"top""top"::266266,,"left""left"::628628,,"height""height"::4444}}}},,{{"char""char"::""公公"",,"location""location"::{{"width""width"::2727,,"top""top"::266266,,"left""left"::668668,,"height""height"::4444}}}},,{{"char""char"::""告告"",,"location""location"::{{"width""width"::2626,,"top""top"::266266,,"left""left"::709709,,"height""height"::4444}}

图像

55

Page 56: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

}}]],,"location""location"::{{"width""width"::201201,,"top""top"::266266,,"left""left"::535535,,"height""height"::4444}},,"words""words"::""新新服公告新新服公告""}},,{{"chars""chars"::[[{{"char""char"::""承承"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::984984,,"height""height"::4343}}}},,{{"char""char"::""载载"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::10231023,,"height""height"::4343}}}},,{{"char""char"::""六六"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::10631063,,"height""height"::4343}}}},,{{"char""char"::""⼤⼤"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::10901090,,"height""height"::4343}}}},,{{"char""char"::""种种"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::11161116,,"height""height"::4343}}}},,{{"char""char"::""族族"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::11551155,,"height""height"::4343}}}},,{{"char""char"::""的的"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::11811181,,"height""height"::4343}}}},,{{"char""char"::""重重"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::12201220,,"height""height"::4343}}}},,{{"char""char"::""⽣⽣"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::12601260,,"height""height"::4343}}}},,{{"char""char"::""之之"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::12861286,,"height""height"::4343}}}},,{{"char""char"::""使使"",,"location""location"::{{"width""width"::2727,,"top""top"::282282,,"left""left"::13251325,,"height""height"::4343}}}},,{{"char""char"::""命命"",,

图像

56

Page 57: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::13511351,,"height""height"::4343}}}},,{{"char""char"::","",",,"location""location"::{{"width""width"::2121,,"top""top"::282282,,"left""left"::13851385,,"height""height"::4343}}}},,{{"char""char"::""超超"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::14161416,,"height""height"::4343}}}},,{{"char""char"::""现现"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::14561456,,"height""height"::4343}}}},,{{"char""char"::""实实"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::14831483,,"height""height"::4343}}}},,{{"char""char"::"3""3",,"location""location"::{{"width""width"::2222,,"top""top"::282282,,"left""left"::15171517,,"height""height"::4343}}}},,{{"char""char"::"D""D",,"location""location"::{{"width""width"::2121,,"top""top"::282282,,"left""left"::15311531,,"height""height"::4343}}}},,{{"char""char"::""魔魔"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::15601560,,"height""height"::4343}}}},,{{"char""char"::"M""M",,"location""location"::{{"width""width"::6161,,"top""top"::284284,,"left""left"::15831583,,"height""height"::4040}}}},,{{"char""char"::"M""M",,"location""location"::{{"width""width"::3535,,"top""top"::284284,,"left""left"::16391639,,"height""height"::4040}}}},,{{"char""char"::"O""O",,"location""location"::{{"width""width"::3131,,"top""top"::284284,,"left""left"::16691669,,"height""height"::4040}}}},,{{"char""char"::"A""A",,"location""location"::{{"width""width"::2525,,"top""top"::284284,,"left""left"::16961696,,"height""height"::4040}}}},,{{"char""char"::"R""R",,"location""location"::{{"width""width"::2525,,"top""top"::284284,,"left""left"::17161716,,"height""height"::4040}}}},,{{"char""char"::"P""P",,"location""location"::{{"width""width"::2525,,"top""top"::284284,,"left""left"::17351735,,"height""height"::4040}}

图像

57

Page 58: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

}},,{{"char""char"::"G""G",,"location""location"::{{"width""width"::2525,,"top""top"::284284,,"left""left"::17551755,,"height""height"::4040}}}},,{{"char""char"::""幻幻"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::15881588,,"height""height"::4343}}}},,{{"char""char"::""⼿⼿"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::17841784,,"height""height"::4343}}}},,{{"char""char"::""游游"",,"location""location"::{{"width""width"::2626,,"top""top"::282282,,"left""left"::18231823,,"height""height"::4343}}}}]],,"location""location"::{{"width""width"::867867,,"top""top"::282282,,"left""left"::984984,,"height""height"::4343}},,"words""words"::""承载六⼤种族的重⽣之使命承载六⼤种族的重⽣之使命,,超现实超现实3D3D魔魔MMOARPGMMOARPG幻⼿游幻⼿游""}},,{{"chars""chars"::[[{{"char""char"::""不不"",,"location""location"::{{"width""width"::3737,,"top""top"::337337,,"left""left"::923923,,"height""height"::4040}}}},,{{"char""char"::""负负"",,"location""location"::{{"width""width"::2323,,"top""top"::337337,,"left""left"::959959,,"height""height"::4040}}}},,{{"char""char"::""觉觉"",,"location""location"::{{"width""width"::2525,,"top""top"::337337,,"left""left"::996996,,"height""height"::4040}}}},,{{"char""char"::""醒醒"",,"location""location"::{{"width""width"::2323,,"top""top"::337337,,"left""left"::10211021,,"height""height"::4040}}}},,{{"char""char"::""勇勇"",,"location""location"::{{"width""width"::2323,,"top""top"::337337,,"left""left"::10581058,,"height""height"::4040}}}},,{{"char""char"::""⼠⼠"",,"location""location"::{{"width""width"::2525,,"top""top"::337337,,"left""left"::10941094,,"height""height"::4040}}}},,{{"char""char"::""们们"",,"location""location"::{{"width""width"::2525,,"top""top"::337337,,"left""left"::11191119,,"height""height"::4040}}}},,{{"char""char"::""的的"",,

图像

58

Page 59: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"location""location"::{{"width""width"::2525,,"top""top"::337337,,"left""left"::11561156,,"height""height"::4040}}}},,{{"char""char"::""使使"",,"location""location"::{{"width""width"::2525,,"top""top"::337337,,"left""left"::11921192,,"height""height"::4040}}}},,{{"char""char"::""命命"",,"location""location"::{{"width""width"::2525,,"top""top"::337337,,"left""left"::12301230,,"height""height"::4040}}}},,{{"char""char"::""之之"",,"location""location"::{{"width""width"::2525,,"top""top"::337337,,"left""left"::12541254,,"height""height"::4040}}}},,{{"char""char"::""约约"",,"location""location"::{{"width""width"::2525,,"top""top"::337337,,"left""left"::12921292,,"height""height"::4040}}}},,{{"char""char"::","",",,"location""location"::{{"width""width"::2020,,"top""top"::337337,,"left""left"::13241324,,"height""height"::4040}}}},,{{"char""char"::""震震"",,"location""location"::{{"width""width"::2525,,"top""top"::337337,,"left""left"::13531353,,"height""height"::4040}}}},,{{"char""char"::""撼撼"",,"location""location"::{{"width""width"::2525,,"top""top"::337337,,"left""left"::13901390,,"height""height"::4040}}}},,{{"char""char"::""来来"",,"location""location"::{{"width""width"::2323,,"top""top"::337337,,"left""left"::14281428,,"height""height"::4040}}}},,{{"char""char"::""袭袭"",,"location""location"::{{"width""width"::2525,,"top""top"::337337,,"left""left"::14521452,,"height""height"::4040}}}},,{{"char""char"::""。。"",,"location""location"::{{"width""width"::1818,,"top""top"::337337,,"left""left"::14851485,,"height""height"::4040}}}}]],,"location""location"::{{"width""width"::580580,,"top""top"::337337,,"left""left"::923923,,"height""height"::4040}},,"words""words"::""不负觉醒勇⼠们的使命之约不负觉醒勇⼠们的使命之约,,震撼来袭。震撼来袭。""}},,{{"chars""chars"::[[{{"char""char"::""最最"",,"location""location"::{{"width""width"::2020,,"top""top"::364364,,"left""left"::535535,,"height""height"::3333}}}}]],,

图像

59

Page 60: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"location""location"::{{"width""width"::3333,,"top""top"::364364,,"left""left"::535535,,"height""height"::3333}},,"words""words"::""最最""}},,{{"chars""chars"::[[{{"char""char"::""新新"",,"location""location"::{{"width""width"::2626,,"top""top"::389389,,"left""left"::535535,,"height""height"::4343}}}},,{{"char""char"::""违违"",,"location""location"::{{"width""width"::2626,,"top""top"::389389,,"left""left"::588588,,"height""height"::4343}}}},,{{"char""char"::""规规"",,"location""location"::{{"width""width"::2525,,"top""top"::389389,,"left""left"::627627,,"height""height"::4343}}}},,{{"char""char"::""发发"",,"location""location"::{{"width""width"::2626,,"top""top"::389389,,"left""left"::666666,,"height""height"::4343}}}},,{{"char""char"::""⾔⾔"",,"location""location"::{{"width""width"::2626,,"top""top"::389389,,"left""left"::704704,,"height""height"::4343}}}},,{{"char""char"::""处处"",,"location""location"::{{"width""width"::2626,,"top""top"::389389,,"left""left"::743743,,"height""height"::4343}}}},,{{"char""char"::""理理"",,"location""location"::{{"width""width"::2626,,"top""top"::389389,,"left""left"::770770,,"height""height"::4343}}}},,{{"char""char"::""机机"",,"location""location"::{{"width""width"::2626,,"top""top"::389389,,"left""left"::808808,,"height""height"::4343}}}},,{{"char""char"::""制制"",,"location""location"::{{"width""width"::2626,,"top""top"::389389,,"left""left"::848848,,"height""height"::4343}}}}]],,"location""location"::{{"width""width"::343343,,"top""top"::389389,,"left""left"::535535,,"height""height"::4343}},,"words""words"::""新违规发⾔处理机制新违规发⾔处理机制""}},,{{"chars""chars"::[[{{"char""char"::""【【"",,"location""location"::{{"width""width"::2121,,"top""top"::387387,,"left""left"::997997,,"height""height"::4343}}}},,{{"char""char"::""普普"",,

图像

60

Page 61: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"location""location"::{{"width""width"::2525,,"top""top"::387387,,"left""left"::10231023,,"height""height"::4343}}}},,{{"char""char"::""纳纳"",,"location""location"::{{"width""width"::2626,,"top""top"::387387,,"left""left"::10611061,,"height""height"::4343}}}},,{{"char""char"::""⼭⼭"",,"location""location"::{{"width""width"::2525,,"top""top"::387387,,"left""left"::10871087,,"height""height"::4343}}}},,{{"char""char"::""⾕⾕"",,"location""location"::{{"width""width"::2626,,"top""top"::387387,,"left""left"::11261126,,"height""height"::4343}}}},,{{"char""char"::"1""1",,"location""location"::{{"width""width"::2121,,"top""top"::387387,,"left""left"::11481148,,"height""height"::4343}}}},,{{"char""char"::"2""2",,"location""location"::{{"width""width"::2121,,"top""top"::387387,,"left""left"::11601160,,"height""height"::4343}}}},,{{"char""char"::"0""0",,"location""location"::{{"width""width"::2121,,"top""top"::387387,,"left""left"::11871187,,"height""height"::4343}}}},,{{"char""char"::""服服"",,"location""location"::{{"width""width"::2626,,"top""top"::387387,,"left""left"::12041204,,"height""height"::4343}}}},,{{"char""char"::""】】"",,"location""location"::{{"width""width"::2121,,"top""top"::387387,,"left""left"::12381238,,"height""height"::4343}}}},,{{"char""char"::""将将"",,"location""location"::{{"width""width"::2525,,"top""top"::387387,,"left""left"::12691269,,"height""height"::4343}}}},,{{"char""char"::""于于"",,"location""location"::{{"width""width"::2626,,"top""top"::387387,,"left""left"::13081308,,"height""height"::4343}}}},,{{"char""char"::"0""0",,"location""location"::{{"width""width"::2020,,"top""top"::387387,,"left""left"::13291329,,"height""height"::4343}}}},,{{"char""char"::"7""7",,"location""location"::{{"width""width"::2121,,"top""top"::387387,,"left""left"::13551355,,"height""height"::4343}}}},,{{"char""char"::""⽉⽉"",,"location""location"::{{"width""width"::2525,,"top""top"::387387,,"left""left"::13851385,,"height""height"::4343}}

图像

61

Page 62: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

}},,{{"char""char"::"0""0",,"location""location"::{{"width""width"::2121,,"top""top"::387387,,"left""left"::14061406,,"height""height"::4343}}}},,{{"char""char"::"8""8",,"location""location"::{{"width""width"::2121,,"top""top"::387387,,"left""left"::14201420,,"height""height"::4343}}}},,{{"char""char"::""⽇⽇"",,"location""location"::{{"width""width"::2525,,"top""top"::387387,,"left""left"::14511451,,"height""height"::4343}}}},,{{"char""char"::"0""0",,"location""location"::{{"width""width"::2121,,"top""top"::387387,,"left""left"::14711471,,"height""height"::4343}}}},,{{"char""char"::"0""0",,"location""location"::{{"width""width"::2121,,"top""top"::387387,,"left""left"::14971497,,"height""height"::4343}}}},,{{"char""char"::":"":",,"location""location"::{{"width""width"::2121,,"top""top"::387387,,"left""left"::15101510,,"height""height"::4343}}}},,{{"char""char"::"1""1",,"location""location"::{{"width""width"::2121,,"top""top"::387387,,"left""left"::15231523,,"height""height"::4343}}}},,{{"char""char"::"5""5",,"location""location"::{{"width""width"::2121,,"top""top"::387387,,"left""left"::15351535,,"height""height"::4343}}}},,{{"char""char"::""震震"",,"location""location"::{{"width""width"::2525,,"top""top"::387387,,"left""left"::15671567,,"height""height"::4343}}}},,{{"char""char"::""撼撼"",,"location""location"::{{"width""width"::2626,,"top""top"::387387,,"left""left"::15921592,,"height""height"::4343}}}},,{{"char""char"::""开开"",,"location""location"::{{"width""width"::2525,,"top""top"::387387,,"left""left"::16311631,,"height""height"::4343}}}},,{{"char""char"::""启启"",,"location""location"::{{"width""width"::2626,,"top""top"::387387,,"left""left"::16561656,,"height""height"::4343}}}},,{{"char""char"::""。。"",,"location""location"::{{"width""width"::2121,,"top""top"::387387,,"left""left"::16781678,,"height""height"::4343}}}}

图像

62

Page 63: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

]],,"location""location"::{{"width""width"::711711,,"top""top"::387387,,"left""left"::997997,,"height""height"::4343}},,"words""words"::""【普纳⼭⾕【普纳⼭⾕120120服】将于服】将于0707⽉⽉0808⽇⽇00:1500:15震撼开启。震撼开启。""}},,{{"chars""chars"::[[{{"char""char"::""各各"",,"location""location"::{{"width""width"::2323,,"top""top"::438438,,"left""left"::987987,,"height""height"::4040}}}},,{{"char""char"::""位位"",,"location""location"::{{"width""width"::2525,,"top""top"::438438,,"left""left"::10221022,,"height""height"::4040}}}},,{{"char""char"::""勇勇"",,"location""location"::{{"width""width"::2525,,"top""top"::438438,,"left""left"::10591059,,"height""height"::4040}}}},,{{"char""char"::""⼠⼠"",,"location""location"::{{"width""width"::2525,,"top""top"::438438,,"left""left"::10951095,,"height""height"::4040}}}},,{{"char""char"::""请请"",,"location""location"::{{"width""width"::2525,,"top""top"::438438,,"left""left"::11201120,,"height""height"::4040}}}},,{{"char""char"::""拿拿"",,"location""location"::{{"width""width"::2323,,"top""top"::438438,,"left""left"::11571157,,"height""height"::4040}}}},,{{"char""char"::""起起"",,"location""location"::{{"width""width"::2525,,"top""top"::438438,,"left""left"::11811181,,"height""height"::4040}}}},,{{"char""char"::""⼿⼿"",,"location""location"::{{"width""width"::2323,,"top""top"::438438,,"left""left"::12301230,,"height""height"::4040}}}},,{{"char""char"::""中中"",,"location""location"::{{"width""width"::2323,,"top""top"::438438,,"left""left"::12551255,,"height""height"::4040}}}},,{{"char""char"::""武武"",,"location""location"::{{"width""width"::2525,,"top""top"::438438,,"left""left"::12911291,,"height""height"::4040}}}},,{{"char""char"::""器器"",,"location""location"::{{"width""width"::2323,,"top""top"::438438,,"left""left"::13161316,,"height""height"::4040}}}},,{{"char""char"::","",",,"location""location"::{{"width""width"::2020,,"top""top"::438438,,"left""left"::13481348,,"height""height"::4040}}

图像

63

Page 64: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

}},,{{"char""char"::""与与"",,"location""location"::{{"width""width"::2525,,"top""top"::438438,,"left""left"::13891389,,"height""height"::4040}}}},,{{"char""char"::""我我"",,"location""location"::{{"width""width"::2323,,"top""top"::438438,,"left""left"::14141414,,"height""height"::4040}}}},,{{"char""char"::""们们"",,"location""location"::{{"width""width"::2525,,"top""top"::438438,,"left""left"::14491449,,"height""height"::4040}}}},,{{"char""char"::""⼀⼀"",,"location""location"::{{"width""width"::2323,,"top""top"::438438,,"left""left"::14871487,,"height""height"::4040}}}},,{{"char""char"::""同同"",,"location""location"::{{"width""width"::2323,,"top""top"::438438,,"left""left"::15241524,,"height""height"::4040}}}},,{{"char""char"::""踏踏"",,"location""location"::{{"width""width"::2525,,"top""top"::438438,,"left""left"::15481548,,"height""height"::4040}}}},,{{"char""char"::""上上"",,"location""location"::{{"width""width"::2323,,"top""top"::438438,,"left""left"::15841584,,"height""height"::4040}}}},,{{"char""char"::""王王"",,"location""location"::{{"width""width"::2525,,"top""top"::438438,,"left""left"::16211621,,"height""height"::4040}}}},,{{"char""char"::""者者"",,"location""location"::{{"width""width"::2525,,"top""top"::438438,,"left""left"::16451645,,"height""height"::4040}}}},,{{"char""char"::""觉觉"",,"location""location"::{{"width""width"::2323,,"top""top"::438438,,"left""left"::16831683,,"height""height"::4040}}}},,{{"char""char"::""醒醒"",,"location""location"::{{"width""width"::2525,,"top""top"::438438,,"left""left"::17181718,,"height""height"::4040}}}},,{{"char""char"::""之之"",,"location""location"::{{"width""width"::2323,,"top""top"::438438,,"left""left"::17561756,,"height""height"::4040}}}},,{{"char""char"::""路路"",,"location""location"::{{"width""width"::2525,,"top""top"::438438,,"left""left"::17801780,,"height""height"::4040}}}},,

图像

64

Page 65: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

{{"char""char"::"!""!",,"location""location"::{{"width""width"::2020,,"top""top"::438438,,"left""left"::18131813,,"height""height"::4040}}}}]],,"location""location"::{{"width""width"::853853,,"top""top"::438438,,"left""left"::987987,,"height""height"::4040}},,"words""words"::""各位勇⼠请拿起⼿中武器各位勇⼠请拿起⼿中武器,,与我们⼀同踏上王者觉醒之路与我们⼀同踏上王者觉醒之路!"!"}},,{{"chars""chars"::[[{{"char""char"::""限限"",,"location""location"::{{"width""width"::2121,,"top""top"::486486,,"left""left"::535535,,"height""height"::3535}}}}]],,"location""location"::{{"width""width"::3535,,"top""top"::486486,,"left""left"::535535,,"height""height"::3535}},,"words""words"::""限限""}},,{{"chars""chars"::[[{{"char""char"::""时时"",,"location""location"::{{"width""width"::2626,,"top""top"::512512,,"left""left"::534534,,"height""height"::4242}}}},,{{"char""char"::""新新"",,"location""location"::{{"width""width"::2626,,"top""top"::512512,,"left""left"::597597,,"height""height"::4242}}}},,{{"char""char"::""服服"",,"location""location"::{{"width""width"::2626,,"top""top"::512512,,"left""left"::622622,,"height""height"::4242}}}},,{{"char""char"::""活活"",,"location""location"::{{"width""width"::2525,,"top""top"::512512,,"left""left"::661661,,"height""height"::4242}}}},,{{"char""char"::""动动"",,"location""location"::{{"width""width"::2626,,"top""top"::512512,,"left""left"::699699,,"height""height"::4242}}}}]],,"location""location"::{{"width""width"::202202,,"top""top"::512512,,"left""left"::534534,,"height""height"::4242}},,"words""words"::""时新服活动时新服活动""}},,{{"chars""chars"::[[{{"char""char"::""【【"",,"location""location"::{{"width""width"::2222,,"top""top"::538538,,"left""left"::927927,,"height""height"::4343}}}},,{{"char""char"::""游游"",,"location""location"::{{"width""width"::2626,,"top""top"::538538,,"left""left"::955955,,"height""height"::4343}}

图像

65

Page 66: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

}},,{{"char""char"::""戏戏"",,"location""location"::{{"width""width"::2626,,"top""top"::538538,,"left""left"::994994,,"height""height"::4343}}}},,{{"char""char"::""特特"",,"location""location"::{{"width""width"::2626,,"top""top"::538538,,"left""left"::10201020,,"height""height"::4343}}}},,{{"char""char"::""⾊⾊"",,"location""location"::{{"width""width"::2727,,"top""top"::538538,,"left""left"::10601060,,"height""height"::4343}}}},,{{"char""char"::""】】"",,"location""location"::{{"width""width"::1919,,"top""top"::538538,,"left""left"::10951095,,"height""height"::4343}}}}]],,"location""location"::{{"width""width"::187187,,"top""top"::538538,,"left""left"::927927,,"height""height"::4343}},,"words""words"::""【游戏特⾊】【游戏特⾊】""}},,{{"chars""chars"::[[{{"char""char"::""⽕⽕"",,"location""location"::{{"width""width"::2020,,"top""top"::612612,,"left""left"::537537,,"height""height"::3333}}}}]],,"location""location"::{{"width""width"::3333,,"top""top"::612612,,"left""left"::537537,,"height""height"::3333}},,"words""words"::""⽕⽕""}},,{{"chars""chars"::[[{{"char""char"::"1""1",,"location""location"::{{"width""width"::2121,,"top""top"::588588,,"left""left"::992992,,"height""height"::4343}}}},,{{"char""char"::"."".",,"location""location"::{{"width""width"::2121,,"top""top"::588588,,"left""left"::10051005,,"height""height"::4343}}}},,{{"char""char"::""超超"",,"location""location"::{{"width""width"::2626,,"top""top"::588588,,"left""left"::10361036,,"height""height"::4343}}}},,{{"char""char"::""宏宏"",,"location""location"::{{"width""width"::2626,,"top""top"::588588,,"left""left"::10761076,,"height""height"::4343}}}},,{{"char""char"::""伟伟"",,"location""location"::{{"width""width"::2626,,"top""top"::588588,,"left""left"::11011101,,"height""height"::4343}}}},,

图像

66

Page 67: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

{{"char""char"::""世世"",,"location""location"::{{"width""width"::2626,,"top""top"::588588,,"left""left"::11411141,,"height""height"::4343}}}},,{{"char""char"::""界界"",,"location""location"::{{"width""width"::2626,,"top""top"::588588,,"left""left"::11671167,,"height""height"::4343}}}},,{{"char""char"::""观观"",,"location""location"::{{"width""width"::2626,,"top""top"::588588,,"left""left"::12061206,,"height""height"::4343}}}},,{{"char""char"::""、、"",,"location""location"::{{"width""width"::2121,,"top""top"::588588,,"left""left"::12281228,,"height""height"::4343}}}},,{{"char""char"::""六六"",,"location""location"::{{"width""width"::2626,,"top""top"::588588,,"left""left"::12711271,,"height""height"::4343}}}},,{{"char""char"::""⼤⼤"",,"location""location"::{{"width""width"::2626,,"top""top"::588588,,"left""left"::12971297,,"height""height"::4343}}}},,{{"char""char"::""种种"",,"location""location"::{{"width""width"::2626,,"top""top"::588588,,"left""left"::13371337,,"height""height"::4343}}}},,{{"char""char"::""族族"",,"location""location"::{{"width""width"::2626,,"top""top"::588588,,"left""left"::13631363,,"height""height"::4343}}}},,{{"char""char"::""秘秘"",,"location""location"::{{"width""width"::2626,,"top""top"::588588,,"left""left"::14031403,,"height""height"::4343}}}},,{{"char""char"::""密密"",,"location""location"::{{"width""width"::2626,,"top""top"::588588,,"left""left"::14291429,,"height""height"::4343}}}},,{{"char""char"::""等等"",,"location""location"::{{"width""width"::2626,,"top""top"::588588,,"left""left"::14681468,,"height""height"::4343}}}},,{{"char""char"::""你你"",,"location""location"::{{"width""width"::2626,,"top""top"::588588,,"left""left"::14931493,,"height""height"::4343}}}},,{{"char""char"::""探探"",,"location""location"::{{"width""width"::2626,,"top""top"::588588,,"left""left"::15331533,,"height""height"::4343}}}},,{{

图像

67

Page 68: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"char""char"::""索索"",,"location""location"::{{"width""width"::2626,,"top""top"::588588,,"left""left"::15591559,,"height""height"::4343}}}},,{{"char""char"::";"";",,"location""location"::{{"width""width"::1818,,"top""top"::588588,,"left""left"::15951595,,"height""height"::4343}}}}]],,"location""location"::{{"width""width"::642642,,"top""top"::588588,,"left""left"::971971,,"height""height"::4343}},,"words""words"::"1."1.超宏伟世界观、六⼤种族秘密等你探索超宏伟世界观、六⼤种族秘密等你探索;";"}},,{{"chars""chars"::[[{{"char""char"::""爆爆"",,"location""location"::{{"width""width"::2727,,"top""top"::635635,,"left""left"::534534,,"height""height"::4444}}}},,{{"char""char"::""严严"",,"location""location"::{{"width""width"::2727,,"top""top"::635635,,"left""left"::588588,,"height""height"::4444}}}},,{{"char""char"::""禁禁"",,"location""location"::{{"width""width"::2626,,"top""top"::635635,,"left""left"::628628,,"height""height"::4444}}}},,{{"char""char"::""代代"",,"location""location"::{{"width""width"::2727,,"top""top"::635635,,"left""left"::668668,,"height""height"::4444}}}},,{{"char""char"::""充充"",,"location""location"::{{"width""width"::2727,,"top""top"::635635,,"left""left"::708708,,"height""height"::4444}}}},,{{"char""char"::""公公"",,"location""location"::{{"width""width"::2626,,"top""top"::635635,,"left""left"::735735,,"height""height"::4444}}}},,{{"char""char"::""告告"",,"location""location"::{{"width""width"::2727,,"top""top"::635635,,"left""left"::774774,,"height""height"::4444}}}}]],,"location""location"::{{"width""width"::273273,,"top""top"::635635,,"left""left"::534534,,"height""height"::4444}},,"words""words"::""爆严禁代充公告爆严禁代充公告""}},,{{"chars""chars"::[[{{"char""char"::"2""2",,"location""location"::{{"width""width"::2222,,"top""top"::642642,,"left""left"::992992,,"height""height"::4343}}}},,{{"char""char"::"."".",,

图像

68

Page 69: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"location""location"::{{"width""width"::2121,,"top""top"::642642,,"left""left"::10151015,,"height""height"::4343}}}},,{{"char""char"::""全全"",,"location""location"::{{"width""width"::2626,,"top""top"::642642,,"left""left"::10321032,,"height""height"::4343}}}},,{{"char""char"::""⺠⺠"",,"location""location"::{{"width""width"::2626,,"top""top"::642642,,"left""left"::10721072,,"height""height"::4343}}}},,{{"char""char"::""打打"",,"location""location"::{{"width""width"::2626,,"top""top"::642642,,"left""left"::10991099,,"height""height"::4343}}}},,{{"char""char"::""宝宝"",,"location""location"::{{"width""width"::2727,,"top""top"::642642,,"left""left"::11381138,,"height""height"::4343}}}},,{{"char""char"::""得得"",,"location""location"::{{"width""width"::2626,,"top""top"::642642,,"left""left"::11651165,,"height""height"::4343}}}},,{{"char""char"::""神神"",,"location""location"::{{"width""width"::2727,,"top""top"::642642,,"left""left"::12041204,,"height""height"::4343}}}},,{{"char""char"::""装装"",,"location""location"::{{"width""width"::2626,,"top""top"::642642,,"left""left"::12311231,,"height""height"::4343}}}},,{{"char""char"::","",",,"location""location"::{{"width""width"::2121,,"top""top"::642642,,"left""left"::12671267,,"height""height"::4343}}}},,{{"char""char"::""⾃⾃"",,"location""location"::{{"width""width"::2626,,"top""top"::642642,,"left""left"::12971297,,"height""height"::4343}}}},,{{"char""char"::""由由"",,"location""location"::{{"width""width"::2626,,"top""top"::642642,,"left""left"::13371337,,"height""height"::4343}}}},,{{"char""char"::""交交"",,"location""location"::{{"width""width"::2626,,"top""top"::642642,,"left""left"::13641364,,"height""height"::4343}}}},,{{"char""char"::""易易"",,"location""location"::{{"width""width"::2727,,"top""top"::642642,,"left""left"::14031403,,"height""height"::4343}}}},,{{"char""char"::""换换"",,"location""location"::{{"width""width"::2727,,"top""top"::642642,,"left""left"::14291429,,"height""height"::4343}}

图像

69

Page 70: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

}},,{{"char""char"::""货货"",,"location""location"::{{"width""width"::2727,,"top""top"::642642,,"left""left"::14691469,,"height""height"::4343}}}},,{{"char""char"::""币币"",,"location""location"::{{"width""width"::2626,,"top""top"::642642,,"left""left"::14961496,,"height""height"::4343}}}},,{{"char""char"::","",",,"location""location"::{{"width""width"::2121,,"top""top"::642642,,"left""left"::15321532,,"height""height"::4343}}}},,{{"char""char"::""极极"",,"location""location"::{{"width""width"::2626,,"top""top"::642642,,"left""left"::15631563,,"height""height"::4343}}}},,{{"char""char"::""速速"",,"location""location"::{{"width""width"::2626,,"top""top"::642642,,"left""left"::15891589,,"height""height"::4343}}}},,{{"char""char"::""致致"",,"location""location"::{{"width""width"::2626,,"top""top"::642642,,"left""left"::16291629,,"height""height"::4343}}}},,{{"char""char"::""富富"",,"location""location"::{{"width""width"::2727,,"top""top"::642642,,"left""left"::16681668,,"height""height"::4343}}}},,{{"char""char"::";"";",,"location""location"::{{"width""width"::2222,,"top""top"::642642,,"left""left"::16891689,,"height""height"::4343}}}}]],,"location""location"::{{"width""width"::719719,,"top""top"::642642,,"left""left"::992992,,"height""height"::4343}},,"words""words"::"2."2.全⺠打宝得神装全⺠打宝得神装,,⾃由交易换货币⾃由交易换货币,,极速致富极速致富;";"}},,{{"chars""chars"::[[{{"char""char"::"3""3",,"location""location"::{{"width""width"::2121,,"top""top"::693693,,"left""left"::994994,,"height""height"::4242}}}},,{{"char""char"::"."".",,"location""location"::{{"width""width"::2121,,"top""top"::693693,,"left""left"::10141014,,"height""height"::4242}}}},,{{"char""char"::""神神"",,"location""location"::{{"width""width"::2525,,"top""top"::693693,,"left""left"::10311031,,"height""height"::4242}}}},,{{"char""char"::""装装"",,

图像

70

Page 71: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"location""location"::{{"width""width"::2525,,"top""top"::693693,,"left""left"::10691069,,"height""height"::4242}}}},,{{"char""char"::""极极"",,"location""location"::{{"width""width"::2626,,"top""top"::693693,,"left""left"::10941094,,"height""height"::4242}}}},,{{"char""char"::""速速"",,"location""location"::{{"width""width"::2525,,"top""top"::693693,,"left""left"::11331133,,"height""height"::4242}}}},,{{"char""char"::""进进"",,"location""location"::{{"width""width"::2626,,"top""top"::693693,,"left""left"::11701170,,"height""height"::4242}}}},,{{"char""char"::""阶阶"",,"location""location"::{{"width""width"::2626,,"top""top"::693693,,"left""left"::11951195,,"height""height"::4242}}}},,{{"char""char"::","",",,"location""location"::{{"width""width"::2020,,"top""top"::693693,,"left""left"::12291229,,"height""height"::4242}}}},,{{"char""char"::""炼炼"",,"location""location"::{{"width""width"::2525,,"top""top"::693693,,"left""left"::12591259,,"height""height"::4242}}}},,{{"char""char"::""化化"",,"location""location"::{{"width""width"::2626,,"top""top"::693693,,"left""left"::12961296,,"height""height"::4242}}}},,{{"char""char"::""玩玩"",,"location""location"::{{"width""width"::2525,,"top""top"::693693,,"left""left"::13341334,,"height""height"::4242}}}},,{{"char""char"::""法法"",,"location""location"::{{"width""width"::2525,,"top""top"::693693,,"left""left"::13591359,,"height""height"::4242}}}},,{{"char""char"::""打打"",,"location""location"::{{"width""width"::2626,,"top""top"::693693,,"left""left"::13971397,,"height""height"::4242}}}},,{{"char""char"::""造造"",,"location""location"::{{"width""width"::2525,,"top""top"::693693,,"left""left"::14361436,,"height""height"::4242}}}},,{{"char""char"::""独独"",,"location""location"::{{"width""width"::2525,,"top""top"::693693,,"left""left"::14611461,,"height""height"::4242}}}},,{{"char""char"::""特特"",,"location""location"::{{"width""width"::2626,,"top""top"::693693,,"left""left"::14971497,,"height""height"::4242}}

图像

71

Page 72: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

}},,{{"char""char"::""个个"",,"location""location"::{{"width""width"::2525,,"top""top"::693693,,"left""left"::15361536,,"height""height"::4242}}}},,{{"char""char"::""性性"",,"location""location"::{{"width""width"::2525,,"top""top"::693693,,"left""left"::15611561,,"height""height"::4242}}}},,{{"char""char"::""神神"",,"location""location"::{{"width""width"::2626,,"top""top"::693693,,"left""left"::15991599,,"height""height"::4242}}}},,{{"char""char"::""装装"",,"location""location"::{{"width""width"::2626,,"top""top"::693693,,"left""left"::16241624,,"height""height"::4242}}}},,{{"char""char"::";"";",,"location""location"::{{"width""width"::2121,,"top""top"::693693,,"left""left"::16571657,,"height""height"::4242}}}}]],,"location""location"::{{"width""width"::686686,,"top""top"::693693,,"left""left"::994994,,"height""height"::4242}},,"words""words"::"3."3.神装极速进阶神装极速进阶,,炼化玩法打造独特个性神装炼化玩法打造独特个性神装;";"}},,{{"chars""chars"::[[{{"char""char"::"4""4",,"location""location"::{{"width""width"::1919,,"top""top"::746746,,"left""left"::996996,,"height""height"::3838}}}},,{{"char""char"::"."".",,"location""location"::{{"width""width"::1919,,"top""top"::746746,,"left""left"::10081008,,"height""height"::3838}}}},,{{"char""char"::""独独"",,"location""location"::{{"width""width"::2222,,"top""top"::746746,,"left""left"::10361036,,"height""height"::3838}}}},,{{"char""char"::""创创"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::10701070,,"height""height"::3838}}}},,{{"char""char"::""⼗⼗"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::11061106,,"height""height"::3838}}}},,{{"char""char"::""⼆⼆"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::11411141,,"height""height"::3838}}}},,{{"char""char"::""星星"",,

图像

72

Page 73: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::11651165,,"height""height"::3838}}}},,{{"char""char"::""使使"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::11991199,,"height""height"::3838}}}},,{{"char""char"::""助助"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::12351235,,"height""height"::3838}}}},,{{"char""char"::""战战"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::12701270,,"height""height"::3838}}}},,{{"char""char"::""系系"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::13051305,,"height""height"::3838}}}},,{{"char""char"::""统统"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::13281328,,"height""height"::3838}}}},,{{"char""char"::","",",,"location""location"::{{"width""width"::1919,,"top""top"::746746,,"left""left"::13601360,,"height""height"::3838}}}},,{{"char""char"::""五五"",,"location""location"::{{"width""width"::2222,,"top""top"::746746,,"left""left"::14001400,,"height""height"::3838}}}},,{{"char""char"::""⼤⼤"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::14351435,,"height""height"::3838}}}},,{{"char""char"::""魔魔"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::14571457,,"height""height"::3838}}}},,{{"char""char"::""幻幻"",,"location""location"::{{"width""width"::2222,,"top""top"::746746,,"left""left"::14941494,,"height""height"::3838}}}},,{{"char""char"::""星星"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::15291529,,"height""height"::3838}}}},,{{"char""char"::""使使"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::15641564,,"height""height"::3838}}}},,{{"char""char"::""技技"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::15991599,,"height""height"::3838}}

图像

73

Page 74: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

}},,{{"char""char"::""能能"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::16231623,,"height""height"::3838}}}},,{{"char""char"::""逆逆"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::16591659,,"height""height"::3838}}}},,{{"char""char"::""转转"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::16931693,,"height""height"::3838}}}},,{{"char""char"::""战战"",,"location""location"::{{"width""width"::2323,,"top""top"::746746,,"left""left"::17281728,,"height""height"::3838}}}},,{{"char""char"::""局局"",,"location""location"::{{"width""width"::2222,,"top""top"::746746,,"left""left"::17651765,,"height""height"::3838}}}},,{{"char""char"::";"";",,"location""location"::{{"width""width"::1515,,"top""top"::746746,,"left""left"::17941794,,"height""height"::3838}}}}]],,"location""location"::{{"width""width"::821821,,"top""top"::746746,,"left""left"::989989,,"height""height"::3838}},,"words""words"::"4."4.独创⼗⼆星使助战系统独创⼗⼆星使助战系统,,五⼤魔幻星使技能逆转战局五⼤魔幻星使技能逆转战局;";"}},,{{"chars""chars"::[[{{"char""char"::"5""5",,"location""location"::{{"width""width"::2121,,"top""top"::795795,,"left""left"::992992,,"height""height"::4141}}}},,{{"char""char"::"."".",,"location""location"::{{"width""width"::2121,,"top""top"::795795,,"left""left"::10131013,,"height""height"::4141}}}},,{{"char""char"::""六六"",,"location""location"::{{"width""width"::2525,,"top""top"::795795,,"left""left"::10431043,,"height""height"::4141}}}},,{{"char""char"::""⼤⼤"",,"location""location"::{{"width""width"::2525,,"top""top"::795795,,"left""left"::10671067,,"height""height"::4141}}}},,{{"char""char"::""化化"",,"location""location"::{{"width""width"::2525,,"top""top"::795795,,"left""left"::11031103,,"height""height"::4141}}}},,{{"char""char"::""神神"",,

图像

74

Page 75: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"location""location"::{{"width""width"::2525,,"top""top"::795795,,"left""left"::11281128,,"height""height"::4141}}}},,{{"char""char"::""任任"",,"location""location"::{{"width""width"::2525,,"top""top"::795795,,"left""left"::11661166,,"height""height"::4141}}}},,{{"char""char"::""意意"",,"location""location"::{{"width""width"::2323,,"top""top"::795795,,"left""left"::12041204,,"height""height"::4141}}}},,{{"char""char"::""搭搭"",,"location""location"::{{"width""width"::2525,,"top""top"::795795,,"left""left"::12281228,,"height""height"::4141}}}},,{{"char""char"::""配配"",,"location""location"::{{"width""width"::2525,,"top""top"::795795,,"left""left"::12641264,,"height""height"::4141}}}},,{{"char""char"::","",",,"location""location"::{{"width""width"::2020,,"top""top"::795795,,"left""left"::12971297,,"height""height"::4141}}}},,{{"char""char"::""助助"",,"location""location"::{{"width""width"::2323,,"top""top"::795795,,"left""left"::13271327,,"height""height"::4141}}}},,{{"char""char"::""⼒⼒"",,"location""location"::{{"width""width"::2525,,"top""top"::795795,,"left""left"::13641364,,"height""height"::4141}}}},,{{"char""char"::""培培"",,"location""location"::{{"width""width"::2525,,"top""top"::795795,,"left""left"::14001400,,"height""height"::4141}}}},,{{"char""char"::""养养"",,"location""location"::{{"width""width"::2525,,"top""top"::795795,,"left""left"::14381438,,"height""height"::4141}}}},,{{"char""char"::""个个"",,"location""location"::{{"width""width"::2525,,"top""top"::795795,,"left""left"::14631463,,"height""height"::4141}}}},,{{"char""char"::""性性"",,"location""location"::{{"width""width"::2323,,"top""top"::795795,,"left""left"::15011501,,"height""height"::4141}}}},,{{"char""char"::""化化"",,"location""location"::{{"width""width"::2525,,"top""top"::795795,,"left""left"::15251525,,"height""height"::4141}}}},,{{"char""char"::""职职"",,"location""location"::{{"width""width"::2525,,"top""top"::795795,,"left""left"::15631563,,"height""height"::4141}}

图像

75

Page 76: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

}},,{{"char""char"::""业业"",,"location""location"::{{"width""width"::2525,,"top""top"::795795,,"left""left"::15991599,,"height""height"::4141}}}},,{{"char""char"::""属属"",,"location""location"::{{"width""width"::2323,,"top""top"::795795,,"left""left"::16241624,,"height""height"::4141}}}},,{{"char""char"::""性性"",,"location""location"::{{"width""width"::2525,,"top""top"::795795,,"left""left"::16611661,,"height""height"::4141}}}},,{{"char""char"::";"";",,"location""location"::{{"width""width"::1818,,"top""top"::795795,,"left""left"::16941694,,"height""height"::4141}}}}]],,"location""location"::{{"width""width"::719719,,"top""top"::795795,,"left""left"::992992,,"height""height"::4141}},,"words""words"::"5."5.六⼤化神任意搭配六⼤化神任意搭配,,助⼒培养个性化职业属性助⼒培养个性化职业属性;";"}},,{{"chars""chars"::[[{{"char""char"::"6""6",,"location""location"::{{"width""width"::2020,,"top""top"::844844,,"left""left"::994994,,"height""height"::4242}}}},,{{"char""char"::"."".",,"location""location"::{{"width""width"::2020,,"top""top"::844844,,"left""left"::10141014,,"height""height"::4242}}}},,{{"char""char"::""勇勇"",,"location""location"::{{"width""width"::2525,,"top""top"::844844,,"left""left"::10301030,,"height""height"::4242}}}},,{{"char""char"::""者者"",,"location""location"::{{"width""width"::2626,,"top""top"::844844,,"left""left"::10681068,,"height""height"::4242}}}},,{{"char""char"::""转转"",,"location""location"::{{"width""width"::2525,,"top""top"::844844,,"left""left"::11061106,,"height""height"::4242}}}},,{{"char""char"::""职职"",,"location""location"::{{"width""width"::2525,,"top""top"::844844,,"left""left"::11311131,,"height""height"::4242}}}},,{{"char""char"::""突突"",,"location""location"::{{"width""width"::2626,,"top""top"::844844,,"left""left"::11681168,,"height""height"::4242}}}},,{{"char""char"::""破破"",,

图像

76

Page 77: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"location""location"::{{"width""width"::2626,,"top""top"::844844,,"left""left"::11931193,,"height""height"::4242}}}},,{{"char""char"::""属属"",,"location""location"::{{"width""width"::2525,,"top""top"::844844,,"left""left"::12321232,,"height""height"::4242}}}},,{{"char""char"::""性性"",,"location""location"::{{"width""width"::2525,,"top""top"::844844,,"left""left"::12691269,,"height""height"::4242}}}},,{{"char""char"::","",",,"location""location"::{{"width""width"::2121,,"top""top"::844844,,"left""left"::12911291,,"height""height"::4242}}}},,{{"char""char"::""职职"",,"location""location"::{{"width""width"::2525,,"top""top"::844844,,"left""left"::13331333,,"height""height"::4242}}}},,{{"char""char"::""业业"",,"location""location"::{{"width""width"::2525,,"top""top"::844844,,"left""left"::13711371,,"height""height"::4242}}}},,{{"char""char"::""时时"",,"location""location"::{{"width""width"::2525,,"top""top"::844844,,"left""left"::13961396,,"height""height"::4242}}}},,{{"char""char"::""装装"",,"location""location"::{{"width""width"::2525,,"top""top"::844844,,"left""left"::14331433,,"height""height"::4242}}}},,{{"char""char"::""免免"",,"location""location"::{{"width""width"::3838,,"top""top"::844844,,"left""left"::14591459,,"height""height"::4242}}}},,{{"char""char"::""费费"",,"location""location"::{{"width""width"::2525,,"top""top"::844844,,"left""left"::14961496,,"height""height"::4242}}}},,{{"char""char"::""领领"",,"location""location"::{{"width""width"::2525,,"top""top"::844844,,"left""left"::15341534,,"height""height"::4242}}}},,{{"char""char"::";"";",,"location""location"::{{"width""width"::2121,,"top""top"::844844,,"left""left"::15551555,,"height""height"::4242}}}}]],,"location""location"::{{"width""width"::586586,,"top""top"::844844,,"left""left"::994994,,"height""height"::4242}},,"words""words"::"6."6.勇者转职突破属性勇者转职突破属性,,职业时装免费领职业时装免费领;";"}},,{{"chars""chars"::[[{{

图像

77

Page 78: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"char""char"::"7""7",,"location""location"::{{"width""width"::2323,,"top""top"::893893,,"left""left"::992992,,"height""height"::4646}}}},,{{"char""char"::"."".",,"location""location"::{{"width""width"::2222,,"top""top"::893893,,"left""left"::10021002,,"height""height"::4646}}}},,{{"char""char"::"B""B",,"location""location"::{{"width""width"::2323,,"top""top"::893893,,"left""left"::10291029,,"height""height"::4646}}}},,{{"char""char"::"O""O",,"location""location"::{{"width""width"::2222,,"top""top"::893893,,"left""left"::10441044,,"height""height"::4646}}}},,{{"char""char"::"S""S",,"location""location"::{{"width""width"::2323,,"top""top"::893893,,"left""left"::10711071,,"height""height"::4646}}}},,{{"char""char"::"S""S",,"location""location"::{{"width""width"::2323,,"top""top"::893893,,"left""left"::11001100,,"height""height"::4646}}}},,{{"char""char"::""爆爆"",,"location""location"::{{"width""width"::2828,,"top""top"::893893,,"left""left"::11181118,,"height""height"::4646}}}},,{{"char""char"::""率率"",,"location""location"::{{"width""width"::2727,,"top""top"::893893,,"left""left"::11471147,,"height""height"::4646}}}},,{{"char""char"::"1""1",,"location""location"::{{"width""width"::2222,,"top""top"::893893,,"left""left"::11711171,,"height""height"::4646}}}},,{{"char""char"::"0""0",,"location""location"::{{"width""width"::2222,,"top""top"::893893,,"left""left"::11841184,,"height""height"::4646}}}},,{{"char""char"::"0""0",,"location""location"::{{"width""width"::2323,,"top""top"::893893,,"left""left"::12121212,,"height""height"::4646}}}},,{{"char""char"::"%""%",,"location""location"::{{"width""width"::2828,,"top""top"::893893,,"left""left"::12311231,,"height""height"::4646}}}},,{{"char""char"::","",",,"location""location"::{{"width""width"::2222,,"top""top"::893893,,"left""left"::12551255,,"height""height"::4646}}}},,{{"char""char"::""狂狂"",,

图像

78

Page 79: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"location""location"::{{"width""width"::2828,,"top""top"::893893,,"left""left"::12871287,,"height""height"::4646}}}},,{{"char""char"::""爆爆"",,"location""location"::{{"width""width"::2727,,"top""top"::893893,,"left""left"::13311331,,"height""height"::4646}}}},,{{"char""char"::""极极"",,"location""location"::{{"width""width"::2828,,"top""top"::893893,,"left""left"::13581358,,"height""height"::4646}}}},,{{"char""char"::""品品"",,"location""location"::{{"width""width"::2727,,"top""top"::893893,,"left""left"::13871387,,"height""height"::4646}}}},,{{"char""char"::""装装"",,"location""location"::{{"width""width"::2828,,"top""top"::893893,,"left""left"::14281428,,"height""height"::4646}}}},,{{"char""char"::""备备"",,"location""location"::{{"width""width"::2727,,"top""top"::893893,,"left""left"::14561456,,"height""height"::4646}}}},,{{"char""char"::","",",,"location""location"::{{"width""width"::2222,,"top""top"::893893,,"left""left"::14801480,,"height""height"::4646}}}},,{{"char""char"::""轻轻"",,"location""location"::{{"width""width"::2828,,"top""top"::893893,,"left""left"::15261526,,"height""height"::4646}}}},,{{"char""char"::""松松"",,"location""location"::{{"width""width"::2828,,"top""top"::893893,,"left""left"::15551555,,"height""height"::4646}}}},,{{"char""char"::""集集"",,"location""location"::{{"width""width"::2828,,"top""top"::893893,,"left""left"::15971597,,"height""height"::4646}}}},,{{"char""char"::""⻬⻬"",,"location""location"::{{"width""width"::2828,,"top""top"::893893,,"left""left"::16251625,,"height""height"::4646}}}},,{{"char""char"::""全全"",,"location""location"::{{"width""width"::2828,,"top""top"::893893,,"left""left"::16531653,,"height""height"::4646}}}},,{{"char""char"::""套套"",,"location""location"::{{"width""width"::2727,,"top""top"::893893,,"left""left"::16961696,,"height""height"::4646}}}},,{{"char""char"::""神神"",,"location""location"::{{"width""width"::2828,,"top""top"::893893,,"left""left"::17241724,,"height""height"::4646}}

图像

79

Page 80: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

}},,{{"char""char"::""装装"",,"location""location"::{{"width""width"::2828,,"top""top"::893893,,"left""left"::17521752,,"height""height"::4646}}}},,{{"char""char"::";"";",,"location""location"::{{"width""width"::2323,,"top""top"::893893,,"left""left"::17751775,,"height""height"::4646}}}}]],,"location""location"::{{"width""width"::813813,,"top""top"::893893,,"left""left"::992992,,"height""height"::4646}},,"words""words"::"7.BOSS"7.BOSS爆率爆率100%,100%,狂爆极品装备狂爆极品装备,,轻松集⻬全套神装轻松集⻬全套神装;";"}},,{{"chars""chars"::[[{{"char""char"::"8""8",,"location""location"::{{"width""width"::2525,,"top""top"::945945,,"left""left"::994994,,"height""height"::4949}}}},,{{"char""char"::"."".",,"location""location"::{{"width""width"::2323,,"top""top"::945945,,"left""left"::10081008,,"height""height"::4949}}}},,{{"char""char"::""⾸⾸"",,"location""location"::{{"width""width"::4444,,"top""top"::945945,,"left""left"::10291029,,"height""height"::4949}}}},,{{"char""char"::""⽇⽇"",,"location""location"::{{"width""width"::2929,,"top""top"::945945,,"left""left"::10721072,,"height""height"::4949}}}},,{{"char""char"::""直直"",,"location""location"::{{"width""width"::2929,,"top""top"::945945,,"left""left"::11021102,,"height""height"::4949}}}},,{{"char""char"::""升升"",,"location""location"::{{"width""width"::2929,,"top""top"::945945,,"left""left"::11321132,,"height""height"::4949}}}},,{{"char""char"::"1""1",,"location""location"::{{"width""width"::2323,,"top""top"::945945,,"left""left"::11581158,,"height""height"::4949}}}},,{{"char""char"::"5""5",,"location""location"::{{"width""width"::2525,,"top""top"::945945,,"left""left"::11721172,,"height""height"::4949}}}},,{{"char""char"::"0""0",,"location""location"::{{"width""width"::2525,,"top""top"::945945,,"left""left"::12011201,,"height""height"::4949}}}},,{{"char""char"::""级级"",,

图像

80

Page 81: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"location""location"::{{"width""width"::2929,,"top""top"::945945,,"left""left"::12221222,,"height""height"::4949}}}},,{{"char""char"::","",",,"location""location"::{{"width""width"::2525,,"top""top"::945945,,"left""left"::12471247,,"height""height"::4949}}}},,{{"char""char"::""登登"",,"location""location"::{{"width""width"::3030,,"top""top"::945945,,"left""left"::12811281,,"height""height"::4949}}}},,{{"char""char"::""录录"",,"location""location"::{{"width""width"::2929,,"top""top"::945945,,"left""left"::13271327,,"height""height"::4949}}}},,{{"char""char"::""即即"",,"location""location"::{{"width""width"::2929,,"top""top"::945945,,"left""left"::13571357,,"height""height"::4949}}}},,{{"char""char"::""送送"",,"location""location"::{{"width""width"::2929,,"top""top"::945945,,"left""left"::13871387,,"height""height"::4949}}}},,{{"char""char"::":"":",,"location""location"::{{"width""width"::2323,,"top""top"::945945,,"left""left"::14121412,,"height""height"::4949}}}},,{{"char""char"::""兽兽"",,"location""location"::{{"width""width"::2929,,"top""top"::945945,,"left""left"::14461446,,"height""height"::4949}}}},,{{"char""char"::""王王"",,"location""location"::{{"width""width"::2929,,"top""top"::945945,,"left""left"::14921492,,"height""height"::4949}}}},,{{"char""char"::""天天"",,"location""location"::{{"width""width"::2929,,"top""top"::945945,,"left""left"::15211521,,"height""height"::4949}}}},,{{"char""char"::""神神"",,"location""location"::{{"width""width"::2929,,"top""top"::945945,,"left""left"::15511551,,"height""height"::4949}}}},,{{"char""char"::""、、"",,"location""location"::{{"width""width"::2525,,"top""top"::945945,,"left""left"::15751575,,"height""height"::4949}}}},,{{"char""char"::""春春"",,"location""location"::{{"width""width"::2929,,"top""top"::945945,,"left""left"::16111611,,"height""height"::4949}}}},,{{"char""char"::""⽇⽇"",,"location""location"::{{"width""width"::3030,,"top""top"::945945,,"left""left"::16551655,,"height""height"::4949}}

图像

81

Page 82: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

}},,{{"char""char"::""时时"",,"location""location"::{{"width""width"::2929,,"top""top"::945945,,"left""left"::16861686,,"height""height"::4949}}}},,{{"char""char"::""装装"",,"location""location"::{{"width""width"::2929,,"top""top"::945945,,"left""left"::17161716,,"height""height"::4949}}}},,{{"char""char"::""、、"",,"location""location"::{{"width""width"::2525,,"top""top"::945945,,"left""left"::17401740,,"height""height"::4949}}}},,{{"char""char"::""雪雪"",,"location""location"::{{"width""width"::2929,,"top""top"::945945,,"left""left"::17891789,,"height""height"::4949}}}},,{{"char""char"::""豹豹"",,"location""location"::{{"width""width"::2828,,"top""top"::945945,,"left""left"::18201820,,"height""height"::4949}}}}]],,"location""location"::{{"width""width"::879879,,"top""top"::945945,,"left""left"::968968,,"height""height"::4949}},,"words""words"::"8."8.⾸⽇直升⾸⽇直升150150级级,,登录即送登录即送::兽王天神、春⽇时装、雪豹兽王天神、春⽇时装、雪豹""}}]]}}

计算⽂字的位置

背景:百度OCR返回的⽂字都是json字典,希望能从对应匹配到的单词,找到对应的位置坐标信息

代码:

defdefcalcWordsLocationcalcWordsLocation((selfself,,wordStrwordStr,,curWordsResultcurWordsResult))::"""Calculatewordslocationfromresult"""Calculatewordslocationfromresult

Args:Args:wordStr(str):thewordstocheckwordStr(str):thewordstocheckcurWordsResult(dict):thebaiduOCRresultofcurrentwordscurWordsResult(dict):thebaiduOCRresultofcurrentwordsReturns:Returns:location,atuple(x,y,width,height)location,atuple(x,y,width,height)Raises:Raises:ExamplesExampleswordStr="wordStr="⾸充⾸充""curWordsResult={curWordsResult={"chars":["chars":[{{"char":""char":"寻寻",","location":{"location":{"width":15,"width":15,

图像

82

Page 83: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"top":51,"top":51,"left":725,"left":725,"height":24"height":24}}},},......{{"char":""char":"⾸⾸",","location":{"location":{"width":15,"width":15,"top":51,"top":51,"left":971,"left":971,"height":24"height":24}}},},{{"char":""char":"充充",","location":{"location":{"width":15,"width":15,"top":51,"top":51,"left":986,"left":986,"height":24"height":24}}}}],],"location":{"location":{"width":280,"width":280,"top":51,"top":51,"left":725,"left":725,"height":24"height":24},},"words":""words":"寻宝福利⼤厅商城⾸充寻宝福利⼤厅商城⾸充""}}->(971,51,30,24)->(971,51,30,24)""""""((xx,,yy,,widthwidth,,heightheight))==((00,,00,,00,,00))matchedStrmatchedStr==curWordsResultcurWordsResult[["words""words"]]#Note:forspecial,containmultilplewords,hereonlyprocessfirtwords#Note:forspecial,containmultilplewords,hereonlyprocessfirtwordsfoundWordsfoundWords==rere..searchsearch((wordStrwordStr,,matchedStrmatchedStr))ififfoundWordsfoundWords::logginglogging..debugdebug(("foundWords=%s""foundWords=%s"%%foundWordsfoundWords))

firstMatchedPosfirstMatchedPos==foundWordsfoundWords..startstart(())lastMatchedPoslastMatchedPos==foundWordsfoundWords..endend(())--11

matchedStrLenmatchedStrLen==lenlen((matchedStrmatchedStr))charResultListcharResultList==curWordsResultcurWordsResult[["chars""chars"]]charResultListLencharResultListLen==lenlen((charResultListcharResultList))

firstCharResultfirstCharResult==NoneNone

图像

83

Page 84: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

lastCharResultlastCharResult==NoneNoneififmatchedStrLenmatchedStrLen====charResultListLencharResultListLen::firstCharResultfirstCharResult==charResultListcharResultList[[firstMatchedPosfirstMatchedPos]]lastCharResultlastCharResult==charResultListcharResultList[[lastMatchedPoslastMatchedPos]]elseelse::#Special:for'Loading'matched'Loading',butcharResultListnotincludefi#Special:for'Loading'matched'Loading',butcharResultListnotincludefirstspace'',butfromfisrt='L'toend='g'rstspace'',butfromfisrt='L'toend='g'#sousingfindthecorrespondingchar,thengotitslocation#sousingfindthecorrespondingchar,thengotitslocation#Note:followingmethodnotworkforregexstr,like'^#Note:followingmethodnotworkforregexstr,like'^游戏公告游戏公告$'$'

firtToMatchCharfirtToMatchChar==wordStrwordStr[[00]]lastToMatchCharlastToMatchChar==wordStrwordStr[[--11]]

forforeachCharResulteachCharResultinincharResultListcharResultList::ififfirstCharResultfirstCharResultandandlastCharResultlastCharResult::breakbreak

eachChareachChar==eachCharResulteachCharResult[["char""char"]]ififfirtToMatchCharfirtToMatchChar====eachChareachChar::firstCharResultfirstCharResult==eachCharResulteachCharResultelifeliflastToMatchCharlastToMatchChar====eachChareachChar::lastCharResultlastCharResult==eachCharResulteachCharResult

#Note:follownoneedcheckwords,tosupportinput^#Note:follownoneedcheckwords,tosupportinput^游戏公告游戏公告$tomatch"$tomatch"游戏公告游戏公告""#firstLocation=None#firstLocation=None#lastLocation=None#lastLocation=None#iffirstCharResult["char"]==firtToMatchChar:#iffirstCharResult["char"]==firtToMatchChar:#firstLocation=firstCharResult["location"]#firstLocation=firstCharResult["location"]#iflastCharResult["char"]==lastToMatchChar:#iflastCharResult["char"]==lastToMatchChar:#lastLocation=lastCharResult["location"]#lastLocation=lastCharResult["location"]firstLocationfirstLocation==firstCharResultfirstCharResult[["location""location"]]lastLocationlastLocation==lastCharResultlastCharResult[["location""location"]]

#iffirstLocationandlastLocation:#iffirstLocationandlastLocation:

#supportbothhorizontalandverticalwords#supportbothhorizontalandverticalwordsfirstLeftfirstLeft==firstLocationfirstLocation[["left""left"]]lastLeftlastLeft==lastLocationlastLocation[["left""left"]]minLeftminLeft==minmin((firstLeftfirstLeft,,lastLeftlastLeft))xx==minLeftminLeft

firstHorizontalEndfirstHorizontalEnd==firstLeftfirstLeft++firstLocationfirstLocation[["width""width"]]lastHorizontalEndlastHorizontalEnd==lastLeftlastLeft++lastLocationlastLocation[["width""width"]]maxHorizontalEndmaxHorizontalEnd==maxmax((firstHorizontalEndfirstHorizontalEnd,,lastHorizontalEndlastHorizontalEnd))widthwidth==maxHorizontalEndmaxHorizontalEnd--xx

图像

84

Page 85: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

lastToplastTop==lastLocationlastLocation[["top""top"]]minTopminTop==minmin((firstLocationfirstLocation[["top""top"]],,lastToplastTop))yy==minTopminTop

lastVerticalEndlastVerticalEnd==lastToplastTop++lastLocationlastLocation[["height""height"]]heightheight==lastVerticalEndlastVerticalEnd--yy

returnreturnxx,,yy,,widthwidth,,heightheight

调⽤:

calculatedLocationcalculatedLocation==selfself..calcWordsLocationcalcWordsLocation((eachInputWordseachInputWords,,eachWordsMatchedResulteachWordsMatchedResult))

把坐标位置转成中间坐标值

作⽤:⽤于后续点击按钮中间坐标值

代码:

defdeflocationToCenterPoslocationToCenterPos((selfself,,wordslocationwordslocation))::"""Convertlocationofnormalbuttontocenterposition"""Convertlocationofnormalbuttontocenterposition

Args:Args:wordslocation(tuple):wordslocation,(x,y,width,height)wordslocation(tuple):wordslocation,(x,y,width,height)Example:(267,567,140,39)Example:(267,567,140,39)Returns:Returns:tuple,(x,y),thelocation'scenterposition,normalusedlatertoclickittuple,(x,y),thelocation'scenterposition,normalusedlatertoclickitExample:(337.0,586.5)Example:(337.0,586.5)Raises:Raises:""""""xx,,yy,,widthwidth,,heightheight==wordslocationwordslocationcenterXcenterX==xx++widthwidth//22centerYcenterY==yy++heightheight//22centerPositioncenterPosition==((centerXcenterX,,centerYcenterY))returnreturncenterPositioncenterPosition

调⽤:

curCenterXcurCenterX,,curCenterYcurCenterY==selfself..locationToCenterPoslocationToCenterPos((eachLocationeachLocation))

检测⽂字是否在结果中

代码:

图像

85

Page 86: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

defdefisWordsInResultisWordsInResult((selfself,,respJsonrespJson,,wordsOrWordsListwordsOrWordsList,,isMatchMultipleisMatchMultiple==FalseFalse))::"""Checkwordsisinresultornot"""Checkwordsisinresultornot

Args:Args:respJson(dict):BaiduOCRresponsedjsonrespJson(dict):BaiduOCRresponsedjsonwordsOrWordsList(str/list):singleinputstrorstrlistwordsOrWordsList(str/list):singleinputstrorstrlistisMatchMultiple(bool):foreachsinglestr,tomatchmultipleoutputoronlymatcisMatchMultiple(bool):foreachsinglestr,tomatchmultipleoutputoronlymatchoneoutputhoneoutputReturns:Returns:dict,matchedresultdict,matchedresultRaises:Raises:""""""#Note:useOrderedDictinsteaddicttokeeporder,forlatergetfirstmatchresultt#Note:useOrderedDictinsteaddicttokeeporder,forlatergetfirstmatchresulttoprocessoprocessorderedMatchedResultDictorderedMatchedResultDict==OrderedDictOrderedDict(())

inputWordsListinputWordsList==wordsOrWordsListwordsOrWordsListififisinstanceisinstance((wordsOrWordsListwordsOrWordsList,,strstr))::inputWordsinputWords==strstr((wordsOrWordsListwordsOrWordsList))inputWordsListinputWordsList==[[inputWordsinputWords]]

wordsResultListwordsResultList==respJsonrespJson[["words_result""words_result"]]forforcurInputWordscurInputWordsinininputWordsListinputWordsList::curMatchedResultListcurMatchedResultList==[[]]forforeachWordsResulteachWordsResultininwordsResultListwordsResultList::eachWordseachWords==eachWordsResulteachWordsResult[["words""words"]]foundCurWordsfoundCurWords==rere..searchsearch((curInputWordscurInputWords,,eachWordseachWords))ififfoundCurWordsfoundCurWords::curMatchedResultListcurMatchedResultList..appendappend((eachWordsResulteachWordsResult))ififnotnotisMatchMultipleisMatchMultiple::breakbreak

orderedMatchedResultDictorderedMatchedResultDict[[curInputWordscurInputWords]]==curMatchedResultListcurMatchedResultListreturnreturnorderedMatchedResultDictorderedMatchedResultDict

调⽤:

matchedResultDictmatchedResultDict==selfself..isWordsInResultisWordsInResult((wordsResultJsonwordsResultJson,,wordsOrWordsListwordsOrWordsList,,isMatchMultipleisMatchMultiple))

检测当前屏幕中是否包含对应⽂字

defdefisWordsInCurScreenisWordsInCurScreen((selfself,,wordsOrWordsListwordsOrWordsList,,imgPathimgPath==NoneNone,,isMatchMultipleisMatchMultiple==FalseFalse,,isRespisRespShortInfoShortInfo==FalseFalse))::"""Foundwordsincurrentscreen"""Foundwordsincurrentscreen

图像

86

Page 87: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

Args:Args:wordsOrWordsList(str/list):singleinputstrorstrlistwordsOrWordsList(str/list):singleinputstrorstrlistimgPath(str):currentscreenimagefilepath;default=None;ifNone,willautogeimgPath(str):currentscreenimagefilepath;default=None;ifNone,willautogetcurrentscrrenimagetcurrentscrrenimageisMatchMultiple(bool):foreachsinglestr,tomatchmultipleoutputoronlymatcisMatchMultiple(bool):foreachsinglestr,tomatchmultipleoutputoronlymatchoneoutput;default=Falsehoneoutput;default=FalseisRespShortInfo(bool):returnsimple=short=nomarllyboolorlist[bool]infoorreisRespShortInfo(bool):returnsimple=short=nomarllyboolorlist[bool]infoorreturnfullinfowhichcontainimgPathandfullmatchedresult.turnfullinfowhichcontainimgPathandfullmatchedresult.Returns:Returns:matchedresult,type=bool/list[bool]/dict/tuple,dependsondiffrentconditionmatchedresult,type=bool/list[bool]/dict/tuple,dependsondiffrentconditionRaises:Raises:""""""retValueretValue==NoneNone

ififnotnotimgPathimgPath::#doscreenshot#doscreenshotimgPathimgPath==selfself..getCurScreenshotgetCurScreenshot(())

wordsResultJsonwordsResultJson==selfself..baiduImageToWordsbaiduImageToWords((imgPathimgPath))

isMultipleInputisMultipleInput==FalseFalseinputWordsinputWords==NoneNoneinputWordsListinputWordsList==[[]]

ififisinstanceisinstance((wordsOrWordsListwordsOrWordsList,,listlist))::isMultipleInputisMultipleInput==TrueTrueinputWordsListinputWordsList==listlist((wordsOrWordsListwordsOrWordsList))elifelifisinstanceisinstance((wordsOrWordsListwordsOrWordsList,,strstr))::isMultipleInputisMultipleInput==FalseFalseinputWordsinputWords==strstr((wordsOrWordsListwordsOrWordsList))inputWordsListinputWordsList==[[inputWordsinputWords]]

matchedResultDictmatchedResultDict==selfself..isWordsInResultisWordsInResult((wordsResultJsonwordsResultJson,,wordsOrWordsListwordsOrWordsList,,isMatchMulisMatchMultipletiple))

#addcaclulatedlocationandwords#addcaclulatedlocationandwords#Note:useOrderedDictinsteaddicttokeeporder,forlatergetfirstmatchresultt#Note:useOrderedDictinsteaddicttokeeporder,forlatergetfirstmatchresulttoprocessoprocessprocessedResultDictprocessedResultDict==OrderedDictOrderedDict(())forforeachInputWordseachInputWordsinininputWordsListinputWordsList::isCurFoundisCurFound==FalseFalse#curLocatoinList=[]#curLocatoinList=[]#curWordsList=[]#curWordsList=[]curResultListcurResultList==[[]]

图像

87

Page 88: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

curWordsMatchedResultListcurWordsMatchedResultList==matchedResultDictmatchedResultDict[[eachInputWordseachInputWords]]ififcurWordsMatchedResultListcurWordsMatchedResultList::isCurFoundisCurFound==TrueTrueforforcurIdxcurIdx,,eachWordsMatchedResulteachWordsMatchedResultininenumerateenumerate((curWordsMatchedResultListcurWordsMatchedResultList))::curMatchedWordscurMatchedWords==eachWordsMatchedResulteachWordsMatchedResult[["words""words"]]calculatedLocationcalculatedLocation==selfself..calcWordsLocationcalcWordsLocation((eachInputWordseachInputWords,,eachWordsMatcheachWordsMatchedResultedResult))#curLocatoinList.append(calculatedLocation)#curLocatoinList.append(calculatedLocation)#curWordsList.append(curMatchedWords)#curWordsList.append(curMatchedWords)curResultcurResult==((curMatchedWordscurMatchedWords,,calculatedLocationcalculatedLocation))curResultListcurResultList..appendappend((curResultcurResult))

#processedResultDict[eachInputWords]=(isCurFound,curLocatoinList,curWordsList)#processedResultDict[eachInputWords]=(isCurFound,curLocatoinList,curWordsList)

processedResultDictprocessedResultDict[[eachInputWordseachInputWords]]==((isCurFoundisCurFound,,curResultListcurResultList))logginglogging..debugdebug(("For%s,matchedResult=%sfromimgPath=%s""For%s,matchedResult=%sfromimgPath=%s",,wordsOrWordsListwordsOrWordsList,,processedRprocessedResultDictesultDict,,imgPathimgPath))

ififisMultipleInputisMultipleInput::ififisRespShortInfoisRespShortInfo::isFoundListisFoundList==[[]]forforeachInputWordseachInputWordsininprocessedResultDictprocessedResultDict..keyskeys(())::isCurFoundisCurFound,,noUsenoUse==processedResultDictprocessedResultDict[[eachInputWordseachInputWords]]isFoundListisFoundList..appendappend((isCurFoundisCurFound))#Note:nomattterisMatchMultiple,bothonlyreturnsinglebooleanforeachi#Note:nomattterisMatchMultiple,bothonlyreturnsinglebooleanforeachinputwordsnputwordsretBoolListretBoolList==isFoundListisFoundListretValueretValue==retBoolListretBoolListelseelse::ififisMatchMultipleisMatchMultiple::retTupleretTuple==processedResultDictprocessedResultDict,,imgPathimgPathretValueretValue==retTupleretTupleelseelse::#Note:useOrderedDictinsteaddicttokeeporder,forlatergetfirstma#Note:useOrderedDictinsteaddicttokeeporder,forlatergetfirstmatchresulttoprocesstchresulttoprocessrespResultDictrespResultDict==OrderedDictOrderedDict(())forforeachInputWordseachInputWordsininprocessedResultDictprocessedResultDict..keyskeys(())::#isCurFound,curLocatoinList,curWordsList=processedResultDict[each#isCurFound,curLocatoinList,curWordsList=processedResultDict[eachInputWords]InputWords]isCurFoundisCurFound,,curResultListcurResultList==processedResultDictprocessedResultDict[[eachInputWordseachInputWords]]#singleLocation=None#singleLocation=None#singleWords=None#singleWords=NonesingleResultsingleResult==((NoneNone,,NoneNone))ififisCurFoundisCurFound::#singleLocation=curLocatoinList[0]#singleLocation=curLocatoinList[0]#singleWords=curWordsList[0]#singleWords=curWordsList[0]singleResultsingleResult==curResultListcurResultList[[00]]#respResultDict[eachInputWords]=(isCurFound,singleLocation,single#respResultDict[eachInputWords]=(isCurFound,singleLocation,singleWords)Words)respResultDictrespResultDict[[eachInputWordseachInputWords]]==((isCurFoundisCurFound,,singleResultsingleResult))

图像

88

Page 89: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

retTupleretTuple==respResultDictrespResultDict,,imgPathimgPathretValueretValue==retTupleretTupleelseelse::singleInputResultsingleInputResult==processedResultDictprocessedResultDict[[inputWordsinputWords]]#isCurFound,curLocatoinList,curWordsList=singleInputResult#isCurFound,curLocatoinList,curWordsList=singleInputResultisCurFoundisCurFound,,curResultListcurResultList==singleInputResultsingleInputResultififisRespShortInfoisRespShortInfo::#Note:nomattterisMatchMultiple,bothonlyreturnsinglebooleanforeachi#Note:nomattterisMatchMultiple,bothonlyreturnsinglebooleanforeachinputwordsnputwordsretBoolretBool==isCurFoundisCurFoundretValueretValue==retBoolretBoolelseelse::ififisMatchMultipleisMatchMultiple::#retTuple=isCurFound,curLocatoinList,curWordsList,imgPath#retTuple=isCurFound,curLocatoinList,curWordsList,imgPathretTupleretTuple==isCurFoundisCurFound,,curResultListcurResultList,,imgPathimgPathretValueretValue==retTupleretTupleelseelse::singleResultsingleResult==((NoneNone,,NoneNone))#singleLocation=None#singleLocation=None#singleWords=None#singleWords=NoneififisCurFoundisCurFound::#singleLocation=curLocatoinList[0]#singleLocation=curLocatoinList[0]#singleWords=curWordsList[0]#singleWords=curWordsList[0]singleResultsingleResult==curResultListcurResultList[[00]]#retTuple=isCurFound,singleLocation,singleWords,imgPath#retTuple=isCurFound,singleLocation,singleWords,imgPathretTupleretTuple==isCurFoundisCurFound,,singleResultsingleResult,,imgPathimgPathretValueretValue==retTupleretTuple

logginglogging..debugdebug(("Input:%s,output=%s""Input:%s,output=%s",,wordsOrWordsListwordsOrWordsList,,retValueretValue))returnreturnretValueretValue

调⽤:

allResultDictallResultDict,,__==selfself..isWordsInCurScreenisWordsInCurScreen((allStrListallStrList,,imgPathimgPath,,isMatchMultipleisMatchMultiple==TrueTrue))

获取当前屏幕中的⽂字

defdefgetWordsInCurScreengetWordsInCurScreen((selfself))::"""getwordsincurrentscreenshot""""""getwordsincurrentscreenshot"""screenImgPathscreenImgPath==selfself..getCurScreenshotgetCurScreenshot(())wordsResultJsonwordsResultJson==selfself..baiduImageToWordsbaiduImageToWords((screenImgPathscreenImgPath))returnreturnwordsResultJsonwordsResultJson

调⽤:

curScreenWordscurScreenWords==selfself..getWordsInCurScreengetWordsInCurScreen(())

图像

89

Page 90: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

检测当前屏幕中是否存在某些信息

defdefcheckExistInScreencheckExistInScreen((selfself,,imgPathimgPath==NoneNone,,mandatoryStrListmandatoryStrList==[[]],,mandatoryMinMatchCountmandatoryMinMatchCount==00,,optionalStrListoptionalStrList==[[]],,#optionalMinMatchCount=2,#optionalMinMatchCount=2,optionalMinMatchCountoptionalMinMatchCount==11,,isRespFullInfoisRespFullInfo==FalseFalse))::"""Checkwhethermandatoryandoptionalstrlistincurrentscreenornot"""Checkwhethermandatoryandoptionalstrlistincurrentscreenornot

Args:Args:imgPath(str):currentscreenimagefilepath;default=None;ifNone,willautogeimgPath(str):currentscreenimagefilepath;default=None;ifNone,willautogetcurrentscrrenimagetcurrentscrrenimagemandatoryStrList(list):mandatorystr,atleastmatch`mandatoryMinMatchCount`,omandatoryStrList(list):mandatorystr,atleastmatch`mandatoryMinMatchCount`,orallmustmatchif`mandatoryMinMatchCount`=0rallmustmatchif`mandatoryMinMatchCount`=0mandatoryMinMatchCount(int):minimalmatchcountformandatorylistmandatoryMinMatchCount(int):minimalmatchcountformandatorylistoptionalStrList(list):optionalstr,somemaymatchoptionalStrList(list):optionalstr,somemaymatchoptionalMinMatchCount(int):for`optionalStrList`,theminimalmatchcount,consioptionalMinMatchCount(int):for`optionalStrList`,theminimalmatchcount,considertomatchornotdertomatchornotisRespFullInfo(bool):returnfullinfoornot,fullinfomeansmatchlocationresisRespFullInfo(bool):returnfullinfoornot,fullinfomeansmatchlocationresultandimgPathultandimgPathReturns:Returns:matchedresult,type=bool/tuple,dependson`isRespFullInfo`matchedresult,type=bool/tuple,dependson`isRespFullInfo`Raises:Raises:""""""ififnotnotimgPathimgPath::imgPathimgPath==selfself..getCurScreenshotgetCurScreenshot(())logginglogging..debugdebug(("imgPath=%s""imgPath=%s",,imgPathimgPath))

isExistisExist==FalseFalse#Note:useOrderedDictinsteaddicttokeeporder,forlatergetfirstmatchresultt#Note:useOrderedDictinsteaddicttokeeporder,forlatergetfirstmatchresulttoprocessoprocessrespMatchLocationrespMatchLocation==OrderedDictOrderedDict(())

isMandatoryMatchisMandatoryMatch==TrueTrueisMandatoryShouldMatchAllisMandatoryShouldMatchAll==((mandatoryMinMatchCountmandatoryMinMatchCount<=<=00))isOptionalMatchisOptionalMatch==TrueTrue

allStrListallStrList==[[]]allStrListallStrList..extendextend((mandatoryStrListmandatoryStrList))allStrListallStrList..extendextend((optionalStrListoptionalStrList))

optionalMatchCountoptionalMatchCount==00mandatoryMatchCountmandatoryMatchCount==00

图像

90

Page 91: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

allResultDictallResultDict,,__==selfself..isWordsInCurScreenisWordsInCurScreen((allStrListallStrList,,imgPathimgPath,,isMatchMultipleisMatchMultiple==TrueTrue))forforeachStreachStr,,((isFoundCurisFoundCur,,curResultListcurResultList))ininallResultDictallResultDict..itemsitems(())::ififeachStreachStrininmandatoryStrListmandatoryStrList::ififisFoundCurisFoundCur::mandatoryMatchCountmandatoryMatchCount+=+=11respMatchLocationrespMatchLocation[[eachStreachStr]]==curResultListcurResultListelseelse::ififisMandatoryShouldMatchAllisMandatoryShouldMatchAll::isMandatoryMatchisMandatoryMatch==FalseFalsebreakbreakelifelifeachStreachStrininoptionalStrListoptionalStrList::ififisFoundCurisFoundCur::optionalMatchCountoptionalMatchCount+=+=11respMatchLocationrespMatchLocation[[eachStreachStr]]==curResultListcurResultList

ififmandatoryStrListmandatoryStrList::ififnotnotisMandatoryShouldMatchAllisMandatoryShouldMatchAll::ififmandatoryMatchCountmandatoryMatchCount>=>=mandatoryMinMatchCountmandatoryMinMatchCount::isMandatoryMatchisMandatoryMatch==TrueTrueelseelse::isMandatoryMatchisMandatoryMatch==FalseFalse

ififoptionalStrListoptionalStrList::ififoptionalMatchCountoptionalMatchCount>=>=optionalMinMatchCountoptionalMinMatchCount::isOptionalMatchisOptionalMatch==TrueTrueelseelse::isOptionalMatchisOptionalMatch==FalseFalse

isExistisExist==isMandatoryMatchisMandatoryMatchandandisOptionalMatchisOptionalMatchlogginglogging..debugdebug(("isMandatoryMatch=%s,isOptionalMatch=%s->isExist=%s""isMandatoryMatch=%s,isOptionalMatch=%s->isExist=%s",,isMandatoryMatchisMandatoryMatch,,isOptionalMatchisOptionalMatch,,isExistisExist))

ififisRespFullInfoisRespFullInfo::logginglogging..debugdebug(("mandatoryStrList=%s,optionalStrList=%s->isExist=%s,respMatchLoc"mandatoryStrList=%s,optionalStrList=%s->isExist=%s,respMatchLocation=%s,imgPath=%s"ation=%s,imgPath=%s",,mandatoryStrListmandatoryStrList,,optionalStrListoptionalStrList,,isExistisExist,,respMatchLocationrespMatchLocation,,imgPathimgPath))returnreturn((isExistisExist,,respMatchLocationrespMatchLocation,,imgPathimgPath))elseelse::logginglogging..debugdebug(("mandatoryStrList=%s,optionalStrList=%s->isExist=%s""mandatoryStrList=%s,optionalStrList=%s->isExist=%s",,mandatoryStrListmandatoryStrList,,optionalStrListoptionalStrList,,isExistisExist))returnreturnisExistisExist

调⽤:

checkResultcheckResult==selfself..checkExistInScreencheckExistInScreen((imgPathimgPath==imgPathimgPath,,optionalStrListoptionalStrList==strListstrList,,optionalMinMatchCountoptionalMinMatchCount==11,,

图像

91

Page 92: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

isRespFullInfoisRespFullInfo==isRespFullInfoisRespFullInfo,,))

和:

minOptionalMatchCountminOptionalMatchCount==22

mandatoryListmandatoryList==[[#"#"公告公告",","^"^公告公告$"$",,'^'^强⼒推荐强⼒推荐$'$',,##王城英雄王城英雄,,不规则弹框不规则弹框

。。。。。。

]]

possibleTitleListpossibleTitleList==[["^"^游戏公告游戏公告$"$",,]]optionalListoptionalList==[[]]otherOptionalListotherOptionalList==[[""新增新增((内容内容)?")?",,""游戏特⾊游戏特⾊"",,"("(主要主要)?)?更新更新((内容内容)?")?",,。。。。。。

""登录即送登录即送"",,]]optionalListoptionalList..extendextend((possibleTitleListpossibleTitleList))optionalListoptionalList..extendextend((otherOptionalListotherOptionalList))

checkResultcheckResult==selfself..checkExistInScreencheckExistInScreen((imgPathimgPath==imgPathimgPath,,mandatoryStrListmandatoryStrList==mandatoryListmandatoryList,,mandatoryMinMatchCountmandatoryMinMatchCount==11,,optionalStrListoptionalStrList==optionalListoptionalList,,optionalMinMatchCountoptionalMinMatchCount==minOptionalMatchCountminOptionalMatchCount,,isRespFullInfoisRespFullInfo==isRespFullInfoisRespFullInfo,,))

和:

mandatoryListmandatoryList==[["^"^购买购买$"$",,##造梦⻄游:造梦⻄游:''购买购买''"^"^¥¥\d+\d+元元?"?",,##剑玲珑剑玲珑,,⾄尊屠⻰⾄尊屠⻰

"^\d+"^\d+元元"",,##造梦⻄游:造梦⻄游:'6'6元券元券33元券元券3’3’"^"^充值充值$"$",,##剑玲珑剑玲珑,,⾄尊屠⻰⾄尊屠⻰

]]optionalListoptionalList==[[#common#common""元宝元宝"",,""⽉卡⽉卡"",,。。。。。。

图像

92

Page 93: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

##剑玲珑剑玲珑

""赠赠"",,]]

isRealPayisRealPay,,matchResultmatchResult,,imgPathimgPath==selfself..checkExistInScreencheckExistInScreen((mandatoryStrListmandatoryStrList==mandatoryListmandatoryList,,mandatoryMinMatchCountmandatoryMinMatchCount==22,,optionalStrListoptionalStrList==optionalListoptionalList,,optionalMinMatchCountoptionalMinMatchCount==22,,isRespFullInfoisRespFullInfo==TrueTrue,,))

和:

mandatoryListmandatoryList==[["^(("^((继续继续)|()|(结束结束))$"))$",,##暗⿊觉醒:暗⿊觉醒:''继续继续'or''or'结束结束''"^\d"^\d秒秒$"$",,##暗⿊觉醒:暗⿊觉醒:'5'5秒秒','1','1秒秒'']]

isAutoConverstionisAutoConverstion,,matchResultmatchResult,,imgPathimgPath==selfself..checkExistInScreencheckExistInScreen((imgPathimgPath==imgPathimgPath,,mandatoryStrListmandatoryStrList==mandatoryListmandatoryList,,mandatoryMinMatchCountmandatoryMinMatchCount==22,,isRespFullInfoisRespFullInfo==TrueTrue,,))

和:

mandatoryListmandatoryList==[["^"^充值充值"",,##造梦⻄游:造梦⻄游:""充值战神榜邮件各但充值战神榜邮件各但,,挑战竞技好友挑战竞技好友""""⾸充⾸充$"$",,##剑玲珑,⾄尊屠⻰剑玲珑,⾄尊屠⻰

。。。。。。

]]optionalListoptionalList==[[#common#common""组队组队"",,##⾄尊屠⻰⾄尊屠⻰,,剑玲珑剑玲珑

""任务任务"",,##⾄尊屠⻰⾄尊屠⻰,,剑玲珑剑玲珑

#"#"商城商城",#",#剑玲珑剑玲珑

""寻宝寻宝"",,##剑玲珑剑玲珑

""福利⼤厅福利⼤厅"",,##剑玲珑剑玲珑

。。。。。。

""背包背包"",,]]

isHomeisHome,,matchResultmatchResult,,imgPathimgPath==selfself..checkExistInScreencheckExistInScreen((mandatoryStrListmandatoryStrList==mandatoryListmandatoryList,,mandatoryMinMatchCountmandatoryMinMatchCount==11,,optionalStrListoptionalStrList==optionalListoptionalList,,isRespFullInfoisRespFullInfo==TrueTrue,,))

图像

93

Page 94: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

和:

mandatoryListmandatoryList==[[""⽴即登录⽴即登录"",,##剑玲珑剑玲珑,,⾄尊屠⻰⾄尊屠⻰

。。。。。。

"^"^登录登录$"$",,##暗⿊觉醒暗⿊觉醒

]]optionalListoptionalList==[[#common#common""⼀键⼀键((((注册注册)|()|(试玩试玩))"))",,""忘记密码忘记密码"",,##⾄尊屠⻰⾄尊屠⻰,,⻘云诀⻘云诀

"(("((⽤户⽤户)|()|(账号账号)|()|(⼿机⼿机))))登录登录"",,##剑玲珑剑玲珑,,⾄尊屠⻰⾄尊屠⻰,,""点击选服点击选服"",,##⻘云诀,暗⿊觉醒⻘云诀,暗⿊觉醒

。。。。。。

##造梦⻄游造梦⻄游

""游客登录游客登录"",,##更新:不能⽤游客登录,否则后续⽆法弹出⽀付⻚⾯更新:不能⽤游客登录,否则后续⽆法弹出⽀付⻚⾯

]]

respUserLoginrespUserLogin==selfself..checkExistInScreencheckExistInScreen((mandatoryStrListmandatoryStrList==mandatoryListmandatoryList,,mandatoryMinMatchCountmandatoryMinMatchCount==11,,optionalStrListoptionalStrList==optionalListoptionalList,,isRespFullInfoisRespFullInfo==isRespFullInfoisRespFullInfo))

是否存在任意⼀个词组

defdefisExistAnyStrisExistAnyStr((selfself,,strListstrList,,imgPathimgPath==NoneNone,,isRespFullInfoisRespFullInfo==FalseFalse))::"""Isanystrexistornot"""Isanystrexistornot

Args:Args:strList(list):strlisttocheckexistornotstrList(list):strlisttocheckexistornotimgPath(str):currentscreenimagefilepath;default=None;ifNone,willautogeimgPath(str):currentscreenimagefilepath;default=None;ifNone,willautogetcurrentscrrenimagetcurrentscrrenimageisRespFullInfo(bool):returnfullinfoornot,fullinfomeansmatchlocationresisRespFullInfo(bool):returnfullinfoornot,fullinfomeansmatchlocationresultandimgPathultandimgPathReturns:Returns:matchedresult,type=bool/tuple,dependson`isRespFullInfo`matchedresult,type=bool/tuple,dependson`isRespFullInfo`Raises:Raises:""""""ififnotnotimgPathimgPath::imgPathimgPath==selfself..getCurScreenshotgetCurScreenshot(())

checkResultcheckResult==selfself..checkExistInScreencheckExistInScreen((imgPathimgPath==imgPathimgPath,,optionalStrListoptionalStrList==strListstrList,,optionalMinMatchCountoptionalMinMatchCount==11,,isRespFullInfoisRespFullInfo==isRespFullInfoisRespFullInfo,,))

图像

94

Page 95: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

ififisRespFullInfoisRespFullInfo::isExistAnyisExistAny,,matchResultmatchResult,,imgPathimgPath==checkResultcheckResultlogginglogging..debugdebug(("isExistAny=%s,matchResult=%s,imgPath=%sfor%s""isExistAny=%s,matchResult=%s,imgPath=%sfor%s",,isExistAnyisExistAny,,matcmatchResulthResult,,imgPathimgPath,,strListstrList))returnreturn((isExistAnyisExistAny,,matchResultmatchResult,,imgPathimgPath))elseelse::isExistAnyisExistAny==checkResultcheckResultlogginglogging..debugdebug(("isExistAny=%s,for%s""isExistAny=%s,for%s",,isExistAnyisExistAny,,strListstrList))returnreturnisExistAnyisExistAny

调⽤:

isExistisExist,,matchResultmatchResult,,imgPathimgPath==selfself..isExistAnyStrisExistAnyStr((buttonStrListbuttonStrList,,imgPathimgPath==imgPathimgPath,,isRisRespFullInfoespFullInfo==TrueTrue))

和:

mandatoryListmandatoryList==[[##御剑仙缘御剑仙缘

"""^("""^(请请)?)?点击点击\s?[“”"'][^“”"',]{1,6}[“”"']?"""\s?[“”"'][^“”"',]{1,6}[“”"']?""",,#'#'请点击请点击““战骑战骑'',,''请点击请点击““魂兽魂兽”'”',,''请点击请点击““⼈⼈物物”'”',,''请点击请点击““领取领取”'”',,''请点击请点击““仙盟仙盟”'”',,''点击点击“+”,“+”,放⼊吞噬放⼊吞噬'',,''点击点击““进阶进阶”,”,提升战提升战'',请点击,请点击““每⽇必做每⽇必做””按按]]

respResultrespResult==selfself..isExistAnyStrisExistAnyStr((mandatoryListmandatoryList,,imgPathimgPath==imgPathimgPath,,isRespFullInfoisRespFullInfo==isRespFullIisRespFullInfonfo))

和:

requireManualOperationListrequireManualOperationList==[[""完成指定操作完成指定操作"",,#speical#speical:造梦⻄游:造梦⻄游的的'('(请完成指定操作请完成指定操作))梦⼝梦⼝''的顶部弹框的顶部弹框

]]isRequireManualisRequireManual,,__,,imgPathimgPath==selfself..isExistAnyStrisExistAnyStr((requireManualOperationListrequireManualOperationList,,isRespFullInfoisRespFullInfo==TrueTrue))

和:

lanuchStrListlanuchStrList==[["^4399"^4399⼿机游戏⼿机游戏$"$",,##剑玲珑剑玲珑

"^"^⻄⽠游戏⻄⽠游戏$"$",,##⻘云诀⻘云诀

]]isLaunchisLaunch,,__,,imgPathimgPath==selfself..isExistAnyStrisExistAnyStr((lanuchStrListlanuchStrList,,isRespFullInfoisRespFullInfo==TrueTrue))

和:

loadingStrListloadingStrList==[[##登录类登录类

""正在登录正在登录"",,##正在登录正在登录

"logging""logging",,

图像

95

Page 96: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

。。。。。。

""游戏资源游戏资源"",,##⻘云诀⻘云诀::本地游戏资源已是最新本地游戏资源已是最新

。。。。。。

]]

isLoadingSthisLoadingSth,,__,,imgPathimgPath==selfself..isExistAnyStrisExistAnyStr((loadingStrListloadingStrList,,isRespFullInfoisRespFullInfo==TrueTrue))

和:

gotoPayStrListgotoPayStrList==[["^"^前往充值前往充值$"$",,##剑玲珑剑玲珑

"^"^⽴即充值⽴即充值$"$",,##⾄尊屠⻰⾄尊屠⻰

。。。。。。

]]respBoolOrTuplerespBoolOrTuple==selfself..isExistAnyStrisExistAnyStr((gotoPayStrListgotoPayStrList,,isRespFullInfoisRespFullInfo==isRespLocationisRespLocation))

判断是否所有的字符都存在

defdefisExistAllStrisExistAllStr((selfself,,strListstrList,,imgPathimgPath==NoneNone,,isRespFullInfoisRespFullInfo==FalseFalse))::"""Isallstrexistornot"""Isallstrexistornot

Args:Args:strList(list):strlisttocheckexistornotstrList(list):strlisttocheckexistornotimgPath(str):currentscreenimagefilepath;default=None;ifNone,willautogeimgPath(str):currentscreenimagefilepath;default=None;ifNone,willautogetcurrentscrrenimagetcurrentscrrenimageisRespFullInfo(bool):returnfullinfoornot,fullinfomeansmatchlocationresisRespFullInfo(bool):returnfullinfoornot,fullinfomeansmatchlocationresultandimgPathultandimgPathReturns:Returns:matchedresult,type=bool/tuple,dependson`isRespFullInfo`matchedresult,type=bool/tuple,dependson`isRespFullInfo`Raises:Raises:""""""ififnotnotimgPathimgPath::imgPathimgPath==selfself..getCurScreenshotgetCurScreenshot(())checkResultcheckResult==selfself..checkExistInScreencheckExistInScreen((imgPathimgPath==imgPathimgPath,,mandatoryStrListmandatoryStrList==strListstrList,,isResisRespFullInfopFullInfo==isRespFullInfoisRespFullInfo))ififisRespFullInfoisRespFullInfo::isExistAllisExistAll,,matchResultmatchResult,,imgPathimgPath==checkResultcheckResultlogginglogging..debugdebug(("isExistAll=%s,matchResult=%s,imgPath=%sfor%s""isExistAll=%s,matchResult=%s,imgPath=%sfor%s",,isExistAllisExistAll,,matcmatchResulthResult,,imgPathimgPath,,strListstrList))returnreturn((isExistAllisExistAll,,matchResultmatchResult,,imgPathimgPath))elseelse::isExistAllisExistAll==checkResultcheckResultlogginglogging..debugdebug(("isExistAll=%s,for%s""isExistAll=%s,for%s",,isExistAllisExistAll,,strListstrList))returnreturnisExistAllisExistAll

调⽤:

realPayStrListrealPayStrList==[[

图像

96

Page 97: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"^"^¥¥\d+\d+元元?"?",,##剑玲珑剑玲珑,,⾄尊屠⻰⾄尊屠⻰

"^"^充值充值$"$",,##剑玲珑剑玲珑,,⾄尊屠⻰⾄尊屠⻰

]]returnreturnselfself..isExistAllStrisExistAllStr((realPayStrListrealPayStrList,,isRespFullInfoisRespFullInfo==isRespLocationisRespLocation))

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

图像

97

Page 98: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

⾳频

播放⾳频

树莓派中⽤python播放⾳频

前提:

树莓派中,先去安装vlc:

sudosudoapt-getapt-getinstallinstallvlcvlc

代码:

importimportvlcvlcinstanceinstance==vlcvlc..InstanceInstance(('--aout=alsa''--aout=alsa'))pp==instanceinstance..media_player_newmedia_player_new(())mm==instanceinstance..media_newmedia_new(('/home/pi/Music/lizhongsheng_massif_live.mp3''/home/pi/Music/lizhongsheng_massif_live.mp3'))pp..set_mediaset_media((mm))pp..playplay(())

即可播放⾳频。

实现设置⾳量,暂停,继续播放等操作的代码是:

pp..pausepause(())vlcvlc..libvlc_audio_set_volumelibvlc_audio_set_volume((pp,,4040))pp..playplay(())vlcvlc..libvlc_audio_set_volumelibvlc_audio_set_volume((pp,,9090))

Mac中调⽤mpv播放⾳频

播放⾳频:

cmdPlayercmdPlayer=="mpv""mpv"cmdParaFilePathcmdParaFilePath==tmpAudioFileFullPathtmpAudioFileFullPathcmdArgListcmdArgList==[[cmdPlayercmdPlayer,,cmdParaFilePathcmdParaFilePath]]

ififgCurSubProcessgCurSubProcess::gCurSubProcessgCurSubProcess..terminateterminate(())

gCurSubProcessgCurSubProcess==subprocesssubprocess..PopenPopen((cmdArgListcmdArgList))loglog..debugdebug(("gCurSubProcess=%s""gCurSubProcess=%s",,gCurSubProcessgCurSubProcess))

停⽌播放:

⾳频

98

Page 99: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

ififaudioControlaudioControl===="stop""stop"::ififgCurSubProcessgCurSubProcess::gCurSubProcessgCurSubProcess..terminateterminate(())

respDatarespData=={{audioControlaudioControl::"ok""ok"}}

elseelse::respDatarespData=={{audioControlaudioControl::"Unsupportcommand""Unsupportcommand"}}

获取播放效果:

ififgCurSubProcessgCurSubProcess::isTerminatedisTerminated==gCurSubProcessgCurSubProcess..pollpoll(())#None#None#stdout_data,stderr_data=gCurSubProcess.communicate()#stdout_data,stderr_data=gCurSubProcess.communicate()#stdoutStr=str(stdout_data)#stdoutStr=str(stdout_data)#stderrStr=str(stderr_data)#stderrStr=str(stderr_data)respDatarespData=={{"isTerminated""isTerminated"::isTerminatedisTerminated,,#"stdout_data":stdoutStr,#"stdout_data":stdoutStr,#"stderr_data":stderrStr,#"stderr_data":stderrStr,}}

返回结果:

正在播放:返回isTerminated为 null

被终⽌后,返回isTerminated为 4

⾳频

99

Page 100: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

播放的效果:

mac系统中播放⾳频

PyCharm的console中输出当前播放的信息-》如果是mac的terminal中,则是覆盖式的,不会这么多

⾏同时弹框GUI窗⼝

mp3

⾳频

100

Page 101: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

解析mp3等⾳频⽂件得到时⻓信息

⽤库:

audioreadGitHub

beetbox/audioread:cross-library(GStreamer+CoreAudio+MAD+FFmpeg)audiodecodingforPython

importimportaudioreadaudioread

trytry::audioFullFilePathaudioFullFilePath=="/your/input/audio/file.mp3""/your/input/audio/file.mp3"

withwithaudioreadaudioread..audio_openaudio_open((audioFullFilePathaudioFullFilePath))asasaudioFpaudioFp::audioInfoaudioInfo[["duration""duration"]]==audioFpaudioFp..durationdurationaudioInfoaudioInfo[["channels""channels"]]==audioFpaudioFp..channelschannelsaudioInfoaudioInfo[["sampleRate""sampleRate"]]==audioFpaudioFp..sampleratesamplerate

exceptexceptOSErrorOSErrorasasosErrosErr::logginglogging..errorerror(("OSErrorwhenopen%serror%s""OSErrorwhenopen%serror%s",,audioFullFilePathaudioFullFilePath,,osErrosErr))exceptexceptEOFErrorEOFErrorasaseofErreofErr::logginglogging..errorerror(("EOFErrorwhenopen%serror%s""EOFErrorwhenopen%serror%s",,audioFullFilePathaudioFullFilePath,,eofErreofErr))exceptexceptaudioreadaudioread..DecodeErrorDecodeErrorasasdecodeErrdecodeErr::logginglogging..errorerror(("Decodeaudio%serror%s""Decodeaudio%serror%s",,audioFullFilePathaudioFullFilePath,,decodeErrdecodeErr))

后经整理成函数:

importimportaudioreadaudioread

defdefdetectAudioMetaInfodetectAudioMetaInfo((audioFullPathaudioFullPath))::""""""detectaudiometainfo:duration,channels,sampleRatedetectaudiometainfo:duration,channels,sampleRate""""""isOkisOk==FalseFalseerrMsgerrMsg==""""audioMetaInfoaudioMetaInfo=={{"duration""duration"::00,,"channels""channels"::00,,"sampleRate""sampleRate"::00,,}}

trytry::withwithaudioreadaudioread..audio_openaudio_open((audioFullPathaudioFullPath))asasaudioFpaudioFp::audioMetaInfoaudioMetaInfo[["duration""duration"]]==audioFpaudioFp..durationdurationaudioMetaInfoaudioMetaInfo[["channels""channels"]]==audioFpaudioFp..channelschannelsaudioMetaInfoaudioMetaInfo[["sampleRate""sampleRate"]]==audioFpaudioFp..sampleratesamplerate

isOkisOk==TrueTrueexceptexceptOSErrorOSErrorasasosErrosErr::errMsgerrMsg=="detectaudioinfoerror:%s""detectaudioinfoerror:%s"%%strstr((osErrosErr))

⾳频

101

Page 102: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

exceptexceptEOFErrorEOFErrorasaseofErreofErr::errMsgerrMsg=="detectaudioinfoerror:%s""detectaudioinfoerror:%s"%%strstr((eofErreofErr))exceptexceptaudioreadaudioread..DecodeErrorDecodeErrorasasdecodeErrdecodeErr::errMsgerrMsg=="detectaudioinfoerror:%s""detectaudioinfoerror:%s"%%strstr((decodeErrdecodeErr))

ififisOkisOk::returnreturnisOkisOk,,audioMetaInfoaudioMetaInfoelseelse::returnreturnisOkisOk,,errMsgerrMsg

调⽤:

defdefdemoDetectAudioMetademoDetectAudioMeta(())::curPathcurPath==osos..pathpath..dirnamedirname((__file____file__))inputAudioListinputAudioList==[["input/audio/actual_aac_but_suffix_mp3.mp3""input/audio/actual_aac_but_suffix_mp3.mp3",,"input/audio/real_mp3_format.mp3""input/audio/real_mp3_format.mp3",,"not_exist_audio.wav""not_exist_audio.wav",,"input/audio/fake_audio_actual_image.wav""input/audio/fake_audio_actual_image.wav",,]]

forforeachAudioPatheachAudioPathinininputAudioListinputAudioList::eachAudioFullPatheachAudioFullPath==osos..pathpath..joinjoin((curPathcurPath,,eachAudioPatheachAudioPath))isOkisOk,,errOrInfoerrOrInfo==detectAudioMetaInfodetectAudioMetaInfo((eachAudioFullPatheachAudioFullPath))printprint(("isOk=%s,errOrInfo=%s""isOk=%s,errOrInfo=%s"%%((isOkisOk,,errOrInfoerrOrInfo))))

ifif__name____name__===="__main__""__main__"::demoDetectAudioMetademoDetectAudioMeta(())

对应的⾳频⽂件,⽤MediaInfo检测出的信息:

正常mp3

⾳频

102

Page 103: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

异常mp3:故意把png图⽚改成mp3

⾳频

103

Page 104: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

输出:

#isOk=True,errOrInfo={'duration':637.8,'channels':2,'sampleRate':44100}#isOk=True,errOrInfo={'duration':637.8,'channels':2,'sampleRate':44100}#isOk=True,errOrInfo={'duration':2.3510204081632655,'channels':2,'sampleRate':44100}#isOk=True,errOrInfo={'duration':2.3510204081632655,'channels':2,'sampleRate':44100}

#isOk=False,errOrInfo=detectaudioinfoerror:[Errno2]Nosuchfileordirectory:'/Us#isOk=False,errOrInfo=detectaudioinfoerror:[Errno2]Nosuchfileordirectory:'/Users/crifan/dev/dev_root/crifan/crifanLibPython/crifanLib/demo/not_exist_audio.wav'ers/crifan/dev/dev_root/crifan/crifanLibPython/crifanLib/demo/not_exist_audio.wav'#isOk=False,errOrInfo=detectaudioinfoerror:#isOk=False,errOrInfo=detectaudioinfoerror:

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

⾳频

104

Page 105: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

视频

从视频中提取出⾳频mp3⽂件

importimportososimportimportloggingloggingimportimportsubprocesssubprocess

videoFullpathvideoFullpath=="show_157712932_video.mp4""show_157712932_video.mp4"startTimeStrstartTimeStr=="00:00:11.270""00:00:11.270"#startTimeStr="%02d:%02d:%02d.%03d"%(startTime.hours,startTime.minutes,startTime.se#startTimeStr="%02d:%02d:%02d.%03d"%(startTime.hours,startTime.minutes,startTime.seconds,startTime.milliseconds)conds,startTime.milliseconds)endTimeStrendTimeStr=="00:00:14.550""00:00:14.550"#endTimeStr="%02d:%02d:%02d.%03d"%(endTime.hours,endTime.minutes,endTime.seconds,e#endTimeStr="%02d:%02d:%02d.%03d"%(endTime.hours,endTime.minutes,endTime.seconds,endTime.milliseconds)ndTime.milliseconds)outputAudioFullpathoutputAudioFullpath=="show_157712932_audio_000011270_000014550.mp3""show_157712932_audio_000011270_000014550.mp3"

#extractaudiosegmentfromvideo#extractaudiosegmentfromvideo#ffmpeg-ishow_157712932_video.mp4-ss00:00:11.270-to00:00:14.550-b:a128kshow_1577#ffmpeg-ishow_157712932_video.mp4-ss00:00:11.270-to00:00:14.550-b:a128kshow_157712932_audio_000011270_000014550.mp312932_audio_000011270_000014550.mp3ififnotnotosos..pathpath..existsexists((outputAudioFullpathoutputAudioFullpath))::ffmpegCmdffmpegCmd=="ffmpeg-i%s-ss%s-to%s-b:a128k%s""ffmpeg-i%s-ss%s-to%s-b:a128k%s"%%((videoFullpathvideoFullpath,,startTimeStrstartTimeStr,,endTimeStrendTimeStr,,outputAudioFullpathoutputAudioFullpath))subprocesssubprocess..callcall((ffmpegCmdffmpegCmd,,shellshell==TrueTrue))logginglogging..infoinfo(("Completeuseffmpegextractaudio:%s""Completeuseffmpegextractaudio:%s",,ffmpegCmdffmpegCmd))

可以从mp4中提取出mp3⾳频:

视频

105

Page 106: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

视频

106

Page 107: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

⽹络相关

此处整理和⽹络相关的⼀些常⽤代码段。

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

⽹络相关

107

Page 108: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

BeautifulSoup

⽤⽹络库下载到⻚⾯源码后,就是去解析(HTML等)内容了。

Python中最常⽤的HTML(和XML)解析库之⼀就是: BeautifulSoup

从xml转换出soup

背景:

iOS⾃动化期间,常会涉及到,获取到当前⻚⾯源码,是xml字符串,需要转换为soup,才能后续操作

所以整理出通⽤转换逻辑

defdefxmlToSoupxmlToSoup((xmlStrxmlStr))::"""converttoxmlstringtosoup"""converttoxmlstringtosoupNote:xmlistagcasesensitive->retaintaguppercase->NOTconverttagtolowNote:xmlistagcasesensitive->retaintaguppercase->NOTconverttagtolowercaseercase

Args:Args:xmlStr(str):xmlstr,normallypagesourcexmlStr(str):xmlstr,normallypagesourceReturns:Returns:soupsoupRaises:Raises:""""""#HtmlParser='html.parser'#HtmlParser='html.parser'#XmlParser='xml'#XmlParser='xml'XmlParserXmlParser=='lxml-xml''lxml-xml'curParsercurParser==XmlParserXmlParsersoupsoup==BeautifulSoupBeautifulSoup((xmlStrxmlStr,,curParsercurParser))returnreturnsoupsoup

举例:

(1)

curPageXmlcurPageXml==selfself..get_page_sourceget_page_source(())soupsoup==CommonUtilsCommonUtils..xmlToSoupxmlToSoup((curPageXmlcurPageXml))

获取到xml字符串后,去转换为soup

是否包含符合特定条件的soup节点

defdefisContainSpecificSoupisContainSpecificSoup((soupListsoupList,,elementNameelementName,,isSizeValidCallbackisSizeValidCallback,,matchNummatchNum==11))::""""""判断判断BeautifulSoupBeautifulSoup的的soupsoup的的listlist中,是否包含符合条件的特定的元素:中,是否包含符合条件的特定的元素:

BeautifulSoup

108

Page 109: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

只匹配指定个数的元素才视为找到了只匹配指定个数的元素才视为找到了

元素名相同元素名相同

⾯积⼤⼩是否符合条件⾯积⼤⼩是否符合条件

Args:Args:elementName(str):elementnameelementName(str):elementnameisSizeValidCallback(function):callbackfunctiontocheckwhetherelementsizisSizeValidCallback(function):callbackfunctiontocheckwhetherelementsize(width*height)isvalidornote(width*height)isvalidornotmatchNum(int):souldonlymatchedspecificnumberconsiderasvalidmatchNum(int):souldonlymatchedspecificnumberconsiderasvalidReturns:Returns:boolboolRaises:Raises:""""""isFoundisFound==FalseFalse

matchedSoupListmatchedSoupList==[[]]

forforeachSoupeachSoupininsoupListsoupList::#ifhasattr(eachSoup,"tag"):#ifhasattr(eachSoup,"tag"):ififhasattrhasattr((eachSoupeachSoup,,"name""name"))::#curSoupTag=eachSoup.tag#curSoupTag=eachSoup.tagcurSoupTagcurSoupTag==eachSoupeachSoup..namenameififcurSoupTagcurSoupTag====elementNameelementName::ififhasattrhasattr((eachSoupeachSoup,,"attrs""attrs"))::soupAttrsoupAttr==eachSoupeachSoup..attrsattrssoupWidthsoupWidth==intint((soupAttrsoupAttr[["width""width"]]))soupHeightsoupHeight==intint((soupAttrsoupAttr[["height""height"]]))curSoupSizecurSoupSize==soupWidthsoupWidth**soupHeightsoupHeight#326*270#326*270isSizeValidisSizeValid==isSizeValidCallbackisSizeValidCallback((curSoupSizecurSoupSize))ififisSizeValidisSizeValid::matchedSoupListmatchedSoupList..appendappend((eachSoupeachSoup))

matchedSoupNummatchedSoupNum==lenlen((matchedSoupListmatchedSoupList))ififmatchNummatchNum====00::isFoundisFound==TrueTrueelseelse::ififmatchedSoupNummatchedSoupNum====matchNummatchNum::isFoundisFound==TrueTrue

returnreturnisFoundisFound

说明:

判断soup内,是否有符合特定条件的soup

举例:

(1)iOS的弹框,有上⻆带关闭按钮时,去判断⼀个弹框,是否符合对应条件,以便于判断是否可能

是弹框

nextSiblingeSoupGeneratornextSiblingeSoupGenerator==possibleCloseSouppossibleCloseSoup..next_siblingsnext_siblingsnextSiblingeSoupListnextSiblingeSoupList==listlist((nextSiblingeSoupGeneratornextSiblingeSoupGenerator))

hasLargeImagehasLargeImage==CommonUtilsCommonUtils..isContainSpecificSoupisContainSpecificSoup((nextSiblingeSoupListnextSiblingeSoupList,,"XCUIElementTypeIm"XCUIElementTypeIm

BeautifulSoup

109

Page 110: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

age"age",,selfself..isPopupWindowSizeisPopupWindowSize))isPossibleCloseisPossibleClose==hasLargeImagehasLargeImage

相关函数

defdefisPopupWindowSizeisPopupWindowSize((selfself,,curSizecurSize))::""""""判断⼀个判断⼀个soupsoup的宽⾼⼤⼩是否是弹框类窗⼝的宽⾼⼤⼩是否是弹框类窗⼝(Image,Other(Image,Other等)的⼤⼩等)的⼤⼩""""""#globalFullScreenSize#globalFullScreenSizeFullScreenSizeFullScreenSize==selfself..XX**selfself..totalYtotalYcurSizeRatiocurSizeRatio==curSizecurSize//FullScreenSizeFullScreenSize#0.289#0.289PopupWindowSizeMinRatioPopupWindowSizeMinRatio==0.250.25#PopupWindowSizeMaxRatio=0.9#PopupWindowSizeMaxRatio=0.9PopupWindowSizeMaxRatioPopupWindowSizeMaxRatio==0.80.8#isSizeValid=curSizeRatio>=MinPopupWindowSizeRatio#isSizeValid=curSizeRatio>=MinPopupWindowSizeRatio#ispopuplikewindow,sizeshouldlargeenough,butshouldnotfullscreen#ispopuplikewindow,sizeshouldlargeenough,butshouldnotfullscreenisSizeValidisSizeValid==PopupWindowSizeMinRatioPopupWindowSizeMinRatio<=<=curSizeRatiocurSizeRatio<=<=PopupWindowSizeMaxRatioPopupWindowSizeMaxRatioreturnreturnisSizeValidisSizeValid

(2)

hasNormalButtonhasNormalButton==CommonUtilsCommonUtils..isContainSpecificSoupisContainSpecificSoup((nextSiblingeSoupListnextSiblingeSoupList,,"XCUIElementType"XCUIElementTypeButton"Button",,selfself..isNormalButtonSizeisNormalButtonSize))

相关函数:

defdefisNormalButtonSizeisNormalButtonSize((selfself,,curSizecurSize))::""""""判断⼀个判断⼀个soupsoup的宽⾼⼤⼩是否是普通的按钮⼤⼩的宽⾼⼤⼩是否是普通的按钮⼤⼩""""""NormalButtonSizeMinNormalButtonSizeMin==3030**3030NormalButtonSizeMaxNormalButtonSizeMax==100100**100100isNormalSizeisNormalSize==NormalButtonSizeMinNormalButtonSizeMin<=<=curSizecurSize<=<=NormalButtonSizeMaxNormalButtonSizeMaxreturnreturnisNormalSizeisNormalSize

查找元素,限定条件是符合对应的⼏级的⽗元素的条件

背景:

很多时候,需要对于iOS的app的⻚⾯的源码,即xml中,查找符合特定情况的的元素

这些特定情况,往往是parent或者前⼏层级的parent中,元素符合⼀定条件,往往是type,以及宽度是

屏幕宽度,⾼度是屏幕⾼度等等

所以提取出公共函数,⽤于bs的find查找元素

defdefbsChainFindbsChainFind((curLevelSoupcurLevelSoup,,queryChainListqueryChainList))::"""BeautifulSoupfindwithquerychain"""BeautifulSoupfindwithquerychain

Args:Args:curLevelSoup(soup):BeautifulSoupcurLevelSoup(soup):BeautifulSoupqueryChainList(list):strlistofalllevelquerydictqueryChainList(list):strlistofalllevelquerydict

BeautifulSoup

110

Page 111: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

Returns:Returns:soupsoupRaises:Raises:Examples:Examples:input:input:[[{{"tag":"XCUIElementTypeWindow","tag":"XCUIElementTypeWindow","attrs":{"visible":"true","enabled":"true","width":"%s"%Scre"attrs":{"visible":"true","enabled":"true","width":"%s"%ScreenX,"height":"%s"%ScreenY}enX,"height":"%s"%ScreenY}},},{{"tag":"XCUIElementTypeButton","tag":"XCUIElementTypeButton","attrs":{"visible":"true","enabled":"true","width":"%s"%Scre"attrs":{"visible":"true","enabled":"true","width":"%s"%ScreenX,"height":"%s"%ScreenY}enX,"height":"%s"%ScreenY}},},{{"tag":"XCUIElementTypeStaticText","tag":"XCUIElementTypeStaticText","attrs":{"visible":"true","enabled":"true","value":""attrs":{"visible":"true","enabled":"true","value":"可能离开微信可能离开微信

,打开第三⽅应⽤,打开第三⽅应⽤"}"}},},]]output:output:soupnodeofsoupnodeof<XCUIElementTypeStaticTexttype="XCUIElementTypeStaticText"value="<XCUIElementTypeStaticTexttype="XCUIElementTypeStaticText"value="可能可能

离开微信,打开第三⽅应⽤离开微信,打开第三⽅应⽤"name=""name="可能离开微信,打开第三⽅应⽤可能离开微信,打开第三⽅应⽤"label=""label="可能离开微信,打开第三⽅应⽤可能离开微信,打开第三⽅应⽤""enabled="true"visible="true"x="71"y="331"width="272"height="18"/>enabled="true"visible="true"x="71"y="331"width="272"height="18"/>in:in:<XCUIElementTypeWindowtype="XCUIElementTypeWindow"enabled="true"vis<XCUIElementTypeWindowtype="XCUIElementTypeWindow"enabled="true"visible="true"x="0"y="0"width="414"height="736">ible="true"x="0"y="0"width="414"height="736"><XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"v<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="0"y="0"width="414"height="736">isible="true"x="0"y="0"width="414"height="736"><XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="tru<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="0"y="0"width="414"height="736">e"visible="true"x="0"y="0"width="414"height="736"><XCUIElementTypeOthertype="XCUIElementTypeOther"enabled=<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="0"y="0"width="414"height="736">"true"visible="true"x="0"y="0"width="414"height="736"><XCUIElementTypeButtontype="XCUIElementTypeButton"en<XCUIElementTypeButtontype="XCUIElementTypeButton"enabled="true"visible="true"x="0"y="0"width="414"height="736">abled="true"visible="true"x="0"y="0"width="414"height="736"><XCUIElementTypeStaticTexttype="XCUIElementTypeSt<XCUIElementTypeStaticTexttype="XCUIElementTypeStaticText"enabled="true"visible="false"x="47"y="288"width="0"height="0"/>aticText"enabled="true"visible="false"x="47"y="288"width="0"height="0"/><XCUIElementTypeStaticTexttype="XCUIElementTypeSt<XCUIElementTypeStaticTexttype="XCUIElementTypeStaticText"value="aticText"value="可能离开微信,打开第三⽅应⽤可能离开微信,打开第三⽅应⽤"name=""name="可能离开微信,打开第三⽅应⽤可能离开微信,打开第三⽅应⽤"label=""label="可能离可能离

开微信,打开第三⽅应⽤开微信,打开第三⽅应⽤"enabled="true"visible="true"x="71"y="331"width="272"height="18""enabled="true"visible="true"x="71"y="331"width="272"height="18"/>/><XCUIElementTypeStaticTexttype="XCUIElementTypeSt<XCUIElementTypeStaticTexttype="XCUIElementTypeStaticText"value="aticText"value="取消取消"name=""name="取消取消"label=""label="取消取消"enabled="true"visible="true"x="109"y="409"enabled="true"visible="true"x="109"y="409"width="36"height="22"/>"width="36"height="22"/><XCUIElementTypeStaticTexttype="XCUIElementTypeSt<XCUIElementTypeStaticTexttype="XCUIElementTypeStaticText"value="aticText"value="继续继续"name=""name="继续继续"label=""label="继续继续"enabled="true"visible="true"x="269"y="409"enabled="true"visible="true"x="269"y="409"width="36"height="22"/>"width="36"height="22"/></XCUIElementTypeButton></XCUIElementTypeButton></XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeOther>

BeautifulSoup

111

Page 112: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

</XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeWindow></XCUIElementTypeWindow>""""""foundSoupfoundSoup==NoneNoneififqueryChainListqueryChainList::chainListLenchainListLen==lenlen((queryChainListqueryChainList))

ififchainListLenchainListLen====11::#lastone#lastonecurLevelFindDictcurLevelFindDict==queryChainListqueryChainList[[00]]curTagcurTag==curLevelFindDictcurLevelFindDict[["tag""tag"]]curAttrscurAttrs==curLevelFindDictcurLevelFindDict[["attrs""attrs"]]foundSoupfoundSoup==curLevelSoupcurLevelSoup..findfind((curTagcurTag,,attrsattrs==curAttrscurAttrs))elseelse::highestLevelFindDicthighestLevelFindDict==queryChainListqueryChainList[[00]]curTagcurTag==highestLevelFindDicthighestLevelFindDict[["tag""tag"]]curAttrscurAttrs==highestLevelFindDicthighestLevelFindDict[["attrs""attrs"]]foundSoupListfoundSoupList==curLevelSoupcurLevelSoup..find_allfind_all((curTagcurTag,,attrsattrs==curAttrscurAttrs))ififfoundSoupListfoundSoupList::childrenChainListchildrenChainList==queryChainListqueryChainList[[11::]]forforeachSoupeachSoupininfoundSoupListfoundSoupList::eachSoupResulteachSoupResult==CommonUtilsCommonUtils..bsChainFindbsChainFind((eachSoupeachSoup,,childrenChainLichildrenChainListst))ififeachSoupResulteachSoupResult::foundSoupfoundSoup==eachSoupResulteachSoupResultbreakbreak

returnreturnfoundSoupfoundSoup

举例:

(1)

""""""微信微信--⼩程序⼩程序弹框弹框警告警告尚未进⾏授权:尚未进⾏授权:

<XCUIElementTypeButtontype="XCUIElementTypeButton"enabled="true"visible="true"<XCUIElementTypeButtontype="XCUIElementTypeButton"enabled="true"visible="true"x="0"y="0"width="375"height="667">x="0"y="0"width="375"height="667"><XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="32"y="240"width="311"height="187">"x="32"y="240"width="311"height="187"><XCUIElementTypeImagetype="XCUIElementTypeImage"enabled="true"visible="<XCUIElementTypeImagetype="XCUIElementTypeImage"enabled="true"visible="false"x="32"y="240"width="311"height="187"/>false"x="32"y="240"width="311"height="187"/><XCUIElementTypeStaticTexttype="XCUIElementTypeStaticText"value="<XCUIElementTypeStaticTexttype="XCUIElementTypeStaticText"value="警告警告"na"name="me="警告警告"label=""label="警告警告"enabled="true"visible="true"x="52"y="265"width="271"height="21""enabled="true"visible="true"x="52"y="265"width="271"height="21"/>/><XCUIElementTypeTextViewtype="XCUIElementTypeTextView"value="<XCUIElementTypeTextViewtype="XCUIElementTypeTextView"value="尚未进⾏授权尚未进⾏授权

,请点击确定跳转到授权⻚⾯进⾏授权。,请点击确定跳转到授权⻚⾯进⾏授权。"enabled="true"visible="true"x="60"y="300"width="255""enabled="true"visible="true"x="60"y="300"width="255"height="57"/>height="57"/><XCUIElementTypeButtontype="XCUIElementTypeButton"name="<XCUIElementTypeButtontype="XCUIElementTypeButton"name="取消取消"label=""label="取消取消

"enabled="true"visible="true"x="32"y="376"width="156"height="51"/>"enabled="true"visible="true"x="32"y="376"width="156"height="51"/><XCUIElementTypeButtontype="XCUIElementTypeButton"name="<XCUIElementTypeButtontype="XCUIElementTypeButton"name="确定确定"label=""label="确定确定

"enabled="true"visible="true"x="187"y="376"width="156"height="51"/>"enabled="true"visible="true"x="187"y="376"width="156"height="51"/></XCUIElementTypeOther></XCUIElementTypeOther>

BeautifulSoup

112

Page 113: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

</XCUIElementTypeButton></XCUIElementTypeButton>""""""warningChainListwarningChainList==[[{{"tag""tag"::"XCUIElementTypeButton""XCUIElementTypeButton",,"attrs""attrs"::{{"visible""visible"::"true""true",,"enabled""enabled"::"true""true",,"width""width"::"%s""%s"%%selfself..XX,,"height""height"::"%"%s"s"%%selfself..totalYtotalY}}}},,{{"tag""tag"::"XCUIElementTypeOther""XCUIElementTypeOther",,"attrs""attrs"::{{"visible""visible"::"true""true",,"enabled""enabled"::"true""true"}}}},,{{"tag""tag"::"XCUIElementTypeStaticText""XCUIElementTypeStaticText",,"attrs""attrs"::{{"visible""visible"::"true""true",,"enabled""enabled"::"true""true",,"value""value"::""警告警告""}}}},,]]warningSoupwarningSoup==CommonUtilsCommonUtils..bsChainFindbsChainFind((soupsoup,,warningChainListwarningChainList))

相关:

找到元素后,再去点击:

ififwarningSoupwarningSoup::parentOtherSoupparentOtherSoup==warningSoupwarningSoup..parentparentconfirmSoupconfirmSoup==parentOtherSoupparentOtherSoup..findfind(("XCUIElementTypeButton""XCUIElementTypeButton",,attrsattrs=={{"visible""visible"::"true""true",,"enabled""enabled"::"true""true",,"name""name"::""确定确定""}}))ififconfirmSoupconfirmSoup::selfself..clickElementCenterPositionclickElementCenterPosition((confirmSoupconfirmSoup))foundAndProcessedPopupfoundAndProcessedPopup==TrueTrue

(2)

""""""系统弹框系统弹框拍照或录像:拍照或录像:

<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x=<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="8"y="530"width="398"height="133">"8"y="530"width="398"height="133"><XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="8"y="530"width="398"height="133">"x="8"y="530"width="398"height="133"><XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="8"y="530"width="398"height="133">true"x="8"y="530"width="398"height="133"><XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visib<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="false"x="0"y="0"width="398"height="133">le="false"x="0"y="0"width="398"height="133"><XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"v<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="0"y="0"width="398"height="133">isible="true"x="0"y="0"width="398"height="133"><XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="tru<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="0"y="0"width="398"height="133">e"visible="true"x="0"y="0"width="398"height="133"><XCUIElementTypeOthertype="XCUIElementTypeOther"enabled=<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="0"y="0"width="398"height="133">"true"visible="true"x="0"y="0"width="398"height="133"><XCUIElementTypeOthertype="XCUIElementTypeOther"enab<XCUIElementTypeOthertype="XCUIElementTypeOther"enab

BeautifulSoup

113

Page 114: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

led="true"visible="true"x="0"y="0"width="398"height="133">led="true"visible="true"x="0"y="0"width="398"height="133"><XCUIElementTypeOthertype="XCUIElementTypeOther"<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="0"y="0"width="398"height="133">enabled="true"visible="true"x="0"y="0"width="398"height="133"><XCUIElementTypeTabletype="XCUIElementTypeTab<XCUIElementTypeTabletype="XCUIElementTypeTable"enabled="true"visible="true"x="0"y="0"width="398"height="133">le"enabled="true"visible="true"x="0"y="0"width="398"height="133"><XCUIElementTypeCelltype="XCUIElementType<XCUIElementTypeCelltype="XCUIElementTypeCell"enabled="true"visible="true"x="0"y="0"width="398"height="45">Cell"enabled="true"visible="true"x="0"y="0"width="398"height="45"><XCUIElementTypeOthertype="XCUIElemen<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="0"y="43"width="398"height="2"/>tTypeOther"enabled="true"visible="true"x="0"y="43"width="398"height="2"/><XCUIElementTypeImagetype="XCUIElemen<XCUIElementTypeImagetype="XCUIElementTypeImage"enabled="true"visible="false"x="13"y="6"width="1"height="32"/>tTypeImage"enabled="true"visible="false"x="13"y="6"width="1"height="32"/><XCUIElementTypeStaticTexttype="XCUIE<XCUIElementTypeStaticTexttype="XCUIElementTypeStaticText"value="lementTypeStaticText"value="拍照或录像拍照或录像"name=""name="拍照或录像拍照或录像"label=""label="拍照或录像拍照或录像"enabled="true""enabled="true"visible="true"x="15"y="11"width="87"height="22"/>visible="true"x="15"y="11"width="87"height="22"/><XCUIElementTypeImagetype="XCUIElemen<XCUIElementTypeImagetype="XCUIElementTypeImage"enabled="true"visible="false"x="351"y="6"width="32"height="32"/>tTypeImage"enabled="true"visible="false"x="351"y="6"width="32"height="32"/></XCUIElementTypeCell></XCUIElementTypeCell><XCUIElementTypeCelltype="XCUIElementType<XCUIElementTypeCelltype="XCUIElementTypeCell"enabled="true"visible="true"x="0"y="44"width="398"height="45">Cell"enabled="true"visible="true"x="0"y="44"width="398"height="45"><XCUIElementTypeOthertype="XCUIElemen<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="0"y="88"width="398"height="1"/>tTypeOther"enabled="true"visible="true"x="0"y="88"width="398"height="1"/><XCUIElementTypeImagetype="XCUIElemen<XCUIElementTypeImagetype="XCUIElementTypeImage"enabled="true"visible="false"x="13"y="50"width="1"height="33"/>tTypeImage"enabled="true"visible="false"x="13"y="50"width="1"height="33"/><XCUIElementTypeStaticTexttype="XCUIE<XCUIElementTypeStaticTexttype="XCUIElementTypeStaticText"value="lementTypeStaticText"value="照⽚图库照⽚图库"name=""name="照⽚图库照⽚图库"label=""label="照⽚图库照⽚图库"enabled="true"visibl"enabled="true"visible="true"x="15"y="56"width="70"height="21"/>e="true"x="15"y="56"width="70"height="21"/><XCUIElementTypeImagetype="XCUIElemen<XCUIElementTypeImagetype="XCUIElementTypeImage"enabled="true"visible="false"x="351"y="50"width="32"height="33"/>tTypeImage"enabled="true"visible="false"x="351"y="50"width="32"height="33"/></XCUIElementTypeCell></XCUIElementTypeCell><XCUIElementTypeCelltype="XCUIElementType<XCUIElementTypeCelltype="XCUIElementTypeCell"enabled="true"visible="true"x="0"y="88"width="398"height="45">Cell"enabled="true"visible="true"x="0"y="88"width="398"height="45"><XCUIElementTypeOthertype="XCUIElemen<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="false"x="0"y="132"width="398"height="1"/>tTypeOther"enabled="true"visible="false"x="0"y="132"width="398"height="1"/><XCUIElementTypeImagetype="XCUIElemen<XCUIElementTypeImagetype="XCUIElementTypeImage"enabled="true"visible="false"x="13"y="94"width="1"height="33"/>tTypeImage"enabled="true"visible="false"x="13"y="94"width="1"height="33"/><XCUIElementTypeStaticTexttype="XCUIE<XCUIElementTypeStaticTexttype="XCUIElementTypeStaticText"value="lementTypeStaticText"value="浏览浏览"name=""name="浏览浏览"label=""label="浏览浏览"enabled="true"visible="true"x="enabled="true"visible="true"x="14"y="100"width="36"height="21"/>"14"y="100"width="36"height="21"/><XCUIElementTypeImagetype="XCUIElemen<XCUIElementTypeImagetype="XCUIElementTypeImage"name="UIDocumentPicker-more"enabled="true"visible="false"x="351"y="94"widtTypeImage"name="UIDocumentPicker-more"enabled="true"visible="false"x="351"y="94"width="32"height="33"/>th="32"height="33"/></XCUIElementTypeCell></XCUIElementTypeCell><XCUIElementTypeOthertype="XCUIElementTyp<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="0"y="132"width="398"height="1"/>eOther"enabled="true"visible="true"x="0"y="132"width="398"height="1"/></XCUIElementTypeTable></XCUIElementTypeTable></XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeOther></XCUIElementTypeOther>

BeautifulSoup

114

Page 115: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

</XCUIElementTypeOther></XCUIElementTypeOther><XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x=<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="8"y="671"width="398"height="57">"8"y="671"width="398"height="57"><XCUIElementTypeButtontype="XCUIElementTypeButton"name="<XCUIElementTypeButtontype="XCUIElementTypeButton"name="取消取消"label=""label="取消取消"en"enabled="true"visible="true"x="8"y="671"width="398"height="57"/>abled="true"visible="true"x="8"y="671"width="398"height="57"/></XCUIElementTypeOther></XCUIElementTypeOther>""""""photoCameraChainListphotoCameraChainList==[[{{"tag""tag"::"XCUIElementTypeOther""XCUIElementTypeOther",,"attrs""attrs"::{{"enabled""enabled"::"true""true",,"visible""visible"::"true""true"}}}},,{{"tag""tag"::"XCUIElementTypeTable""XCUIElementTypeTable",,"attrs""attrs"::{{"enabled""enabled"::"true""true",,"visible""visible"::"true""true",,"x""x"::"0""0",,"y""y"::"0""0"}}}},,{{"tag""tag"::"XCUIElementTypeStaticText""XCUIElementTypeStaticText",,"attrs""attrs"::{{"enabled""enabled"::"true""true",,"visible""visible"::"true""true",,"value""value"::""拍照或录像拍照或录像""}}}},,]]photoCameraSoupphotoCameraSoup==CommonUtilsCommonUtils..bsChainFindbsChainFind((soupsoup,,photoCameraChainListphotoCameraChainList))

(3)iOS设置⽆线局域⽹列表⻚找当前已连接的WiFi,特征是带蓝⾊✅ 的:

""""""设置设置⽆线局域⽹⽆线局域⽹列表⻚:列表⻚:

<XCUIElementTypeTabletype="XCUIElementTypeTable"enabled="true"visible="true"x=<XCUIElementTypeTabletype="XCUIElementTypeTable"enabled="true"visible="true"x="0"y="0"width="414"height="736">"0"y="0"width="414"height="736">。。。。。。

<XCUIElementTypeCelltype="XCUIElementTypeCell"name=“xxx_guest_5G,<XCUIElementTypeCelltype="XCUIElementTypeCell"name=“xxx_guest_5G,安全⽹络安全⽹络,,信号强度信号强度33格,共格,共33格格"label=“xxx_guest_5G,"label=“xxx_guest_5G,安全⽹络安全⽹络,,信号强度信号强度33格,共格,共33格格"enabled="true""enabled="true"visible="true"x="0"y="144"width="414"height="43">visible="true"x="0"y="144"width="414"height="43"><XCUIElementTypeStaticTexttype="XCUIElementTypeStaticText"value=“xxx_gue<XCUIElementTypeStaticTexttype="XCUIElementTypeStaticText"value=“xxx_guest_5G"name=“xxx_guest_5G"label=“xxx_guest_5G"enabled="true"visible="true"x="40"y="15st_5G"name=“xxx_guest_5G"label=“xxx_guest_5G"enabled="true"visible="true"x="40"y="155"width="278"height="21"/>5"width="278"height="21"/><XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="0"y="186"width="414"height="1"/>true"x="0"y="186"width="414"height="1"/><XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="true"x="8"y="151"width="28"height="29">true"x="8"y="151"width="28"height="29"><XCUIElementTypeImagetype="XCUIElementTypeImage"name="UIPreferencesB<XCUIElementTypeImagetype="XCUIElementTypeImage"name="UIPreferencesBlueCheck"enabled="true"visible="false"x="8"y="151"width="28"height="29"/>lueCheck"enabled="true"visible="false"x="8"y="151"width="28"height="29"/></XCUIElementTypeOther></XCUIElementTypeOther><XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="<XCUIElementTypeOthertype="XCUIElementTypeOther"enabled="true"visible="false"x="15"y="187"width="245"height="1"/>false"x="15"y="187"width="245"height="1"/><XCUIElementTypeImagetype="XCUIElementTypeImage"name="Lock"enabled="tru<XCUIElementTypeImagetype="XCUIElementTypeImage"name="Lock"enabled="true"visible="false"x="326"y="159"width="8"height="12"/>e"visible="false"x="326"y="159"width="8"height="12"/><XCUIElementTypeImagetype="XCUIElementTypeImage"name="WifiBars3"enabled<XCUIElementTypeImagetype="XCUIElementTypeImage"name="WifiBars3"enabled="true"visible="false"x="346"y="153"width="16"height="25"/>="true"visible="false"x="346"y="153"width="16"height="25"/><XCUIElementTypeButtontype="XCUIElementTypeButton"name="<XCUIElementTypeButtontype="XCUIElementTypeButton"name="更多信息更多信息"label=""label="更多信息更多信息"enabled="true"visible="true"x="372"y="154"width="22"height="22"/>"enabled="true"visible="true"x="372"y="154"width="22"height="22"/></XCUIElementTypeCell></XCUIElementTypeCell>

BeautifulSoup

115

Page 116: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

""""""curPageXmlcurPageXml==selfself..get_page_sourceget_page_source(())soupsoup==CommonUtilsCommonUtils..xmlToSoupxmlToSoup((curPageXmlcurPageXml))blueCheckChainListblueCheckChainList==[[{{"tag""tag"::"XCUIElementTypeCell""XCUIElementTypeCell",,"attrs""attrs"::{{"enabled""enabled"::"true""true",,"visible""visible"::"true""true",,"x""x"::"0""0",,"width""width"::"%s""%s"%%selfself..XX}}}},,{{"tag""tag"::"XCUIElementTypeOther""XCUIElementTypeOther",,"attrs""attrs"::{{"enabled""enabled"::"true""true",,"visible""visible"::"true""true"}}}},,{{"tag""tag"::"XCUIElementTypeImage""XCUIElementTypeImage",,#"attrs":{"enabled":"true","visible":"true","name":"UIPreferencesBlueCheck"}#"attrs":{"enabled":"true","visible":"true","name":"UIPreferencesBlueCheck"}"attrs""attrs"::{{"enabled""enabled"::"true""true",,"name""name"::"UIPreferencesBlueCheck""UIPreferencesBlueCheck"}}}},,]]blueCheckSoupblueCheckSoup==CommonUtilsCommonUtils..bsChainFindbsChainFind((soupsoup,,blueCheckChainListblueCheckChainList))ififblueCheckSoupblueCheckSoup::

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

BeautifulSoup

116

Page 117: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

requests

下载图⽚,保存为⼆进制⽂件

importimportrequestsrequestsrespresp==requestsrequests..getget((pictureUrlpictureUrl))withwithopenopen((saveFullPathsaveFullPath,,'wb''wb'))asassaveFpsaveFp::saveFpsaveFp..writewrite((respresp..contentcontent))

详⻅:

【已解决】Python的requests中如何下载⼆进制数据保存为图⽚⽂件

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

requests

117

Page 118: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

数学

详⻅:

https://github.com/crifan/crifanLibPython/blob/master/crifanLib/crifanMath.py

md5

md5计算

md5

Python3中已改名 hashlib

且update参数只允许 bytes

不允许 str

的md5代码:

fromfromhashlibhashlibimportimportmd5md5#onlyforpython3.x#onlyforpython3.x

defdefgenerateMd5generateMd5((strToMd5strToMd5))::""""""generatemd5stringfrominputstringgeneratemd5stringfrominputstringeg:eg:xxxxxxxx->af0230c7fcc75b34cbb268b9bf64da79xxxxxxxx->af0230c7fcc75b34cbb268b9bf64da79:paramstrToMd5:inputstring:paramstrToMd5:inputstring:return:md5stringof32chars:return:md5stringof32chars""""""encrptedMd5encrptedMd5==""""md5Instancemd5Instance==md5md5(())#print("type(md5Instance)=%s"%type(md5Instance))#type(md5Instance)=<class'_hashl#print("type(md5Instance)=%s"%type(md5Instance))#type(md5Instance)=<class'_hashlib.HASH'>ib.HASH'>#print("type(strToMd5)=%s"%type(strToMd5))#type(strToMd5)=<class'str'>#print("type(strToMd5)=%s"%type(strToMd5))#type(strToMd5)=<class'str'>bytesToMd5bytesToMd5==bytesbytes((strToMd5strToMd5,,"UTF-8""UTF-8"))#print("type(bytesToMd5)=%s"%type(bytesToMd5))#type(bytesToMd5)=<class'bytes'>#print("type(bytesToMd5)=%s"%type(bytesToMd5))#type(bytesToMd5)=<class'bytes'>md5Instancemd5Instance..updateupdate((bytesToMd5bytesToMd5))encrptedMd5encrptedMd5==md5Instancemd5Instance..hexdigesthexdigest(())#print("type(encrptedMd5)=%s"%type(encrptedMd5))#type(encrptedMd5)=<class'str'>#print("type(encrptedMd5)=%s"%type(encrptedMd5))#type(encrptedMd5)=<class'str'>#print("encrptedMd5=%s"%encrptedMd5)#encrptedMd5=3a821616bec2e86e3e232d0c7f392cf5#print("encrptedMd5=%s"%encrptedMd5)#encrptedMd5=3a821616bec2e86e3e232d0c7f392cf5returnreturnencrptedMd5encrptedMd5

之前旧版本的 Python2( <=2.7)版本:

md5还是个独⽴模块

还没有并⼊ hashlib

注:

好像 python2.7中已将md5并⼊ hashlib

数学

118

Page 119: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

但是 update参数还允许 str(⽽不是 bytes)

update参数允许str

的md5代码:

trytry::importimportmd5md5exceptexceptImportErrorImportError::fromfromhashlibhashlibimportimportmd5md5

defdefgenerateMd5generateMd5((strToMd5strToMd5))::encrptedMd5encrptedMd5==""""md5Instancemd5Instance==md5md5..newnew(())#md5Instance=<md5HASHobject@0x1062af738>#md5Instance=<md5HASHobject@0x1062af738>md5Instancemd5Instance..updateupdate((strToMd5strToMd5))encrptedMd5encrptedMd5==md5Instancemd5Instance..hexdigesthexdigest(())#encrptedMd5=af0230c7fcc75b34cbb268b9bf64da79#encrptedMd5=af0230c7fcc75b34cbb268b9bf64da79returnreturnencrptedMd5encrptedMd5

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

数学

119

Page 120: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

常⻅语法

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

常⻅语法

120

Page 121: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

函数参数

可变参数

之前⼀个⽤到了可变参数的函数是:

defdefmultipleRetrymultipleRetry((selfself,,functionInfoDictfunctionInfoDict,,maxRetryNummaxRetryNum==55,,sleepIntervalsleepInterval==0.10.1))::""""""dosomething,retrymutipletimeiffaildosomething,retrymutipletimeiffail

Args:Args:functionInfoDict(dict):functioninfodictcontainfunctionCallbackand[optionalfunctionInfoDict(dict):functioninfodictcontainfunctionCallbackand[optional]functionParaDict]functionParaDictmaxRetryNum(int):maxretrynumbermaxRetryNum(int):maxretrynumbersleepInterval(float):sleeptimeofeachintervalwhenfailsleepInterval(float):sleeptimeofeachintervalwhenfailReturns:Returns:boolboolRaises:Raises:""""""doSuccessdoSuccess==FalseFalsefunctionCallbackfunctionCallback==functionInfoDictfunctionInfoDict[["functionCallback""functionCallback"]]functionParaDictfunctionParaDict==functionInfoDictfunctionInfoDict..getget(("functionParaDict""functionParaDict",,NoneNone))

curRetryNumcurRetryNum==maxRetryNummaxRetryNumwhilewhilecurRetryNumcurRetryNum>>00::ififfunctionParaDictfunctionParaDict::doSuccessdoSuccess==functionCallbackfunctionCallback((****functionParaDictfunctionParaDict))elseelse::doSuccessdoSuccess==functionCallbackfunctionCallback(())

ififdoSuccessdoSuccess::breakbreak

timetime..sleepsleep((sleepIntervalsleepInterval))curRetryNumcurRetryNum-=-=11

ififnotnotdoSuccessdoSuccess::functionNamefunctionName==strstr((functionCallbackfunctionCallback))#'<boundmethodDevicesMethods.switchToAppStoreSearchTabof<src.AppCrawler.AppCr#'<boundmethodDevicesMethods.switchToAppStoreSearchTabof<src.AppCrawler.AppCrawlerobjectat0x1053abe80>>'awlerobjectat0x1053abe80>>'logginglogging..errorerror(("Stillfailafter%dretryfor%s""Stillfailafter%dretryfor%s",,functionNamefunctionName))returnreturndoSuccessdoSuccess

其中的:

functionCallback(**functionParaDict)

中的:

**functionParaDict

函数参数

121

Page 122: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

表示,dict类型的参数,内部包含多个key和value,⽤**去展开后,传⼊真正要执⾏的函数

⼏种调⽤中带参数的例⼦是:

searchInputQuerysearchInputQuery=={{"type""type"::"XCUIElementTypeSearchField""XCUIElementTypeSearchField",,"name""name"::"AppStore""AppStore"}}isInputOkisInputOk==selfself..multipleRetrymultipleRetry(({{"functionCallback""functionCallback"::selfself..wait_element_setTextwait_element_setText,,"functionParaDict""functionParaDict"::{{"locator""locator"::searchInputQuerysearchInputQuery,,"text""text"::appNameappName,,}}}}))

之前原始写法:

searchInputQuerysearchInputQuery=={{"type""type"::"XCUIElementTypeSearchField""XCUIElementTypeSearchField",,"name""name"::"AppStore""AppStore"}}isInputOkisInputOk==selfself..wait_element_setTextwait_element_setText((searchInputQuerysearchInputQuery,,appNameappName))

其中wait_element_setText的定义是:

defdefwait_element_setTextwait_element_setText((selfself,,locatorlocator,,texttext))::

对应着之前传⼊时的:

"functionParaDict""functionParaDict"::{{"locator""locator"::searchInputQuerysearchInputQuery,,"text""text"::appNameappName,,}}

即可,给出上述细节,便于理解,传⼊的参数是如何⽤ **展开的。

详⻅:

【已解决】Python中如何实现函数调⽤时多个可变数量的参数传递

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

函数参数

122

Page 123: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

dict字典

删除dict中某个键(和值)

常⻅写法:

deldelyourDictyourDict[["keyToDelete""keyToDelete"]]

更加Pythonic的写法:

yourDictyourDict..poppop(("keyToDelete""keyToDelete"))

注意:

为了防⽌出现 KeyError,注意确保要删除的key都是存在的,否则就要先判断存在,再去删除。

OrderedDict

想要获取OrderedDict的最后⼀个item(的key和value)

nextnext((reversedreversed((someOrderedDictsomeOrderedDict..itemsitems(())))))

另外,只需要获取最后⼀个元素的key,则可以:

nextnext((reversedreversed((someOrderedDictsomeOrderedDict..keyskeys(())))))

或:

nextnext((reversedreversed((someOrderedDictsomeOrderedDict))))

详⻅:

【已解决】Python中获取OrderedDict中最后⼀个元素

合并2个dict的值

(1)如果⽆需保留原有(第⼀个dict)的值,则⽤update即可:

firstDictfirstDict..updateupdate((secondDictsecondDict))

⽀持: Python>=3.5

(2)如果要保留之前的dict的值,则⽤**展开

dict字典

123

Page 124: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

thirdDictthirdDict==((****firstDictfirstDict,,****secondDictsecondDict))

⽀持: Python2和 Python<=3.4

详⻅:

【已解决】Python中如何合并2个dict字典变量的值

有序字典OrderedDict的初始化

fromfromcollectionscollectionsimportimportOrderedDictOrderedDict

orderedDictorderedDict==OrderedDictOrderedDict(())

后续正常作为普通dict使⽤

>>>>>>fromfromcollectionscollectionsimportimportOrderedDictOrderedDict>>>>>>orderedDictorderedDict==OrderedDictOrderedDict(())>>>>>>orderedDictorderedDict[["key2""key2"]]=="value2""value2">>>>>>orderedDictorderedDict[["key1""key1"]]=="value1""value1">>>>>>orderedDictorderedDict[["key3""key3"]]=="value3""value3">>>>>>orderedDictorderedDictOrderedDictOrderedDict(([[(('key2''key2',,'value2''value2')),,(('key1''key1',,'value1''value1')),,(('key3''key3',,'value3''value3'))]]))

dict的递归的合并更新

defdefrecursiveMergeDictrecursiveMergeDict((aDictaDict,,bDictbDict))::""""""Recursivelymergedictatob,returnmergeddictbRecursivelymergedictatob,returnmergeddictbNote:Subdictandsublist'swon'tbeoverwrittenbutalsoupdated/mergedNote:Subdictandsublist'swon'tbeoverwrittenbutalsoupdated/merged

example:example:(1)inputandoutputexample:(1)inputandoutputexample:input:input:{{"keyStr":"strValueA","keyStr":"strValueA","keyInt":1,"keyInt":1,"keyBool":true,"keyBool":true,"keyList":["keyList":[{{"index0Item1":"index0Item1","index0Item1":"index0Item1","index0Item2":"index0Item2""index0Item2":"index0Item2"},},{{"index1Item1":"index1Item1""index1Item1":"index1Item1"},},{{

dict字典

124

Page 125: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"index2Item1":"index2Item1""index2Item1":"index2Item1"}}]]}}

andand

{{"keyStr":"strValueB","keyStr":"strValueB","keyInt":2,"keyInt":2,"keyList":["keyList":[{{"index0Item1":"index0Item1_b""index0Item1":"index0Item1_b"},},{{"index1Item1":"index1Item1_b""index1Item1":"index1Item1_b"}}]]}}

output:output:

{{"keyStr":"strValueB","keyStr":"strValueB","keyBool":true,"keyBool":true,"keyInt":2,"keyInt":2,"keyList":["keyList":[{{"index0Item1":"index0Item1_b","index0Item1":"index0Item1_b","index0Item2":"index0Item2""index0Item2":"index0Item2"},},{{"index1Item1":"index1Item1_b""index1Item1":"index1Item1_b"},},{{"index2Item1":"index2Item1""index2Item1":"index2Item1"}}]]}}

(2)codeusageexample:(2)codeusageexample:importcopyimportcopycDict=recursiveMergeDict(aDict,copy.deepcopy(bDict))cDict=recursiveMergeDict(aDict,copy.deepcopy(bDict))

Note:Note:bDictshouldusedeepcopy,otherwisewillbealteredaftercallthisfunction!!!bDictshouldusedeepcopy,otherwisewillbealteredaftercallthisfunction!!!

""""""aDictItemsaDictItems==NoneNoneifif((syssys..version_infoversion_info[[00]]====22))::#ispython2#ispython2aDictItemsaDictItems==aDictaDict..iteritemsiteritems(())elseelse::#ispython3#ispython3aDictItemsaDictItems==aDictaDict..itemsitems(())

dict字典

125

Page 126: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

forforaKeyaKey,,aValueaValueininaDictItemsaDictItems::#print("------[%s]=%s"%(aKey,aValue))#print("------[%s]=%s"%(aKey,aValue))ififaKeyaKeynotnotininbDictbDict::bDictbDict[[aKeyaKey]]==aValueaValueelseelse::bValuebValue==bDictbDict[[aKeyaKey]]#print("aValue=%s"%aValue)#print("aValue=%s"%aValue)#print("bValue=%s"%bValue)#print("bValue=%s"%bValue)ififisinstanceisinstance((aValueaValue,,dictdict))::recursiveMergeDictrecursiveMergeDict((aValueaValue,,bValuebValue))elifelifisinstanceisinstance((aValueaValue,,listlist))::aValueListLenaValueListLen==lenlen((aValueaValue))bValueListLenbValueListLen==lenlen((bValuebValue))bValueListMaxIdxbValueListMaxIdx==bValueListLenbValueListLen--11forforaListIdxaListIdxininrangerange((aValueListLenaValueListLen))::#print("---[%d]"%aListIdx)#print("---[%d]"%aListIdx)aListItemaListItem==aValueaValue[[aListIdxaListIdx]]#print("aListItem=%s"%aListItem)#print("aListItem=%s"%aListItem)ififaListIdxaListIdx<=<=bValueListMaxIdxbValueListMaxIdx::bListItembListItem==bValuebValue[[aListIdxaListIdx]]#print("bListItem=%s"%bListItem)#print("bListItem=%s"%bListItem)recursiveMergeDictrecursiveMergeDict((aListItemaListItem,,bListItembListItem))elseelse::#print("bDict=%s"%bDict)#print("bDict=%s"%bDict)#print("aKey=%s"%aKey)#print("aKey=%s"%aKey)#print("aListItem=%s"%aListItem)#print("aListItem=%s"%aListItem)bDictbDict[[aKeyaKey]]..appendappend((aListItemaListItem))

returnreturnbDictbDict

调⽤举例:

templateJsontemplateJson=={{"author""author"::"CrifanLi<[email protected]>""CrifanLi<[email protected]>",,"description""description"::"gitbook"gitbook书的描述书的描述"",,"gitbook""gitbook"::"3.2.3""3.2.3",,"language""language"::"zh-hans""zh-hans",,"links""links"::{{"sidebar""sidebar"::{{""主⻚主⻚""::"http://www.crifan.com""http://www.crifan.com"}}}},,"plugins""plugins"::[["theme-comscore""theme-comscore",,"anchors""anchors",,"-lunr""-lunr",,"-search""-search",,"search-plus""search-plus",,"disqus""disqus",,"-highlight""-highlight",,"prism""prism",,"prism-themes""prism-themes",,"github-buttons""github-buttons",,"splitter""splitter",,

dict字典

126

Page 127: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"-sharing""-sharing",,"sharing-plus""sharing-plus",,"tbfed-pagefooter""tbfed-pagefooter",,"expandable-chapters-small""expandable-chapters-small",,"ga""ga",,"donate""donate",,"sitemap-general""sitemap-general",,"copy-code-button""copy-code-button",,"callouts""callouts",,"toolbar-button""toolbar-button"]],,"pluginsConfig""pluginsConfig"::{{"callouts""callouts"::{{"showTypeInHeader""showTypeInHeader"::falsefalse}},,"disqus""disqus"::{{"shortName""shortName"::"crifan""crifan"}},,"donate""donate"::{{"alipay""alipay"::"https://www.crifan.com/files/res/crifan_com/crifan_alipay_pay.jpg""https://www.crifan.com/files/res/crifan_com/crifan_alipay_pay.jpg",,"alipayText""alipayText"::""⽀付宝打赏给⽀付宝打赏给Crifan"Crifan",,"button""button"::""打赏打赏"",,"title""title"::"""",,"wechat""wechat"::"https://www.crifan.com/files/res/crifan_com/crifan_wechat_pay.jpg""https://www.crifan.com/files/res/crifan_com/crifan_wechat_pay.jpg",,"wechatText""wechatText"::""微信打赏给微信打赏给Crifan"Crifan"}},,"ga""ga"::{{"token""token"::"UA-28297199-1""UA-28297199-1"}},,"github-buttons""github-buttons"::{{"buttons""buttons"::[[{{"count""count"::truetrue,,"repo""repo"::"gitbook_name""gitbook_name",,"size""size"::"small""small",,"type""type"::"star""star",,"user""user"::"crifan""crifan"}},,{{"count""count"::falsefalse,,"size""size"::"small""small",,"type""type"::"follow""follow",,"user""user"::"crifan""crifan",,"width""width"::"120""120"}}]]}},,"prism""prism"::{{"css""css"::[["prism-themes/themes/prism-atom-dark.css""prism-themes/themes/prism-atom-dark.css"]]}},,"sharing""sharing"::{{"all""all"::[["douban""douban",,"facebook""facebook",,"google""google",,"instapaper""instapaper",,"line""line",,"linkedin""linkedin",,"messenger""messenger",,"pocket""pocket",,"qq""qq",,

dict字典

127

Page 128: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"qzone""qzone",,"stumbleupon""stumbleupon",,"twitter""twitter",,"viber""viber",,"vk""vk",,"weibo""weibo",,"whatsapp""whatsapp"]],,"douban""douban"::falsefalse,,"facebook""facebook"::truetrue,,"google""google"::falsefalse,,"hatenaBookmark""hatenaBookmark"::falsefalse,,"instapaper""instapaper"::falsefalse,,"line""line"::falsefalse,,"linkedin""linkedin"::falsefalse,,"messenger""messenger"::falsefalse,,"pocket""pocket"::falsefalse,,"qq""qq"::truetrue,,"qzone""qzone"::falsefalse,,"stumbleupon""stumbleupon"::falsefalse,,"twitter""twitter"::truetrue,,"viber""viber"::falsefalse,,"vk""vk"::falsefalse,,"weibo""weibo"::truetrue,,"whatsapp""whatsapp"::falsefalse}},,"sitemap-general""sitemap-general"::{{"prefix""prefix"::"https://book.crifan.com/gitbook/gitbook_name/website/""https://book.crifan.com/gitbook/gitbook_name/website/"}},,"tbfed-pagefooter""tbfed-pagefooter"::{{"copyright""copyright"::"crifan.com"crifan.com,使⽤,使⽤<a\"href=\"https://creativecommons.org/licenses/by/4.0<a\"href=\"https://creativecommons.org/licenses/by/4.0/deed.zh\">/deed.zh\">署名署名4.04.0国际国际(CC\"BY4.0)(CC\"BY4.0)协议协议</a></a>发布发布"",,"modify_format""modify_format"::"YYYY-MM-DDHH:mm:ss""YYYY-MM-DDHH:mm:ss",,"modify_label""modify_label"::""最后更新:最后更新:""}},,"theme-default""theme-default"::{{"showLevel""showLevel"::truetrue}},,"toolbar-button""toolbar-button"::{{"icon""icon"::"fa-file-pdf-o""fa-file-pdf-o",,"label""label"::""下载下载PDF"PDF",,"url""url"::"http://book.crifan.com/books/gitbook_name/pdf/gitbook_name.pdf""http://book.crifan.com/books/gitbook_name/pdf/gitbook_name.pdf"}}}},,"root""root"::"./src""./src",,"title""title"::"Gitbook"Gitbook的书名的书名""}}

currentJsoncurrentJson=={{"description""description"::"crifan"crifan整理的整理的PythonPython各个⽅⾯常⽤的代码段,供需要的参考。各个⽅⾯常⽤的代码段,供需要的参考。"",,"pluginsConfig""pluginsConfig"::{{"github-buttons""github-buttons"::{{"buttons""buttons"::[[{{"repo""repo"::"python_common_code_snippet""python_common_code_snippet"}}]]}},,"sitemap-general""sitemap-general"::{{"prefix""prefix"::"https://book.crifan.com/gitbook/python_common_code_snippet/website/""https://book.crifan.com/gitbook/python_common_code_snippet/website/"}},,

dict字典

128

Page 129: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

"toolbar-button""toolbar-button"::{{"url""url"::"http://book.crifan.com/books/python_common_code_snippet/pdf/python_common_co"http://book.crifan.com/books/python_common_code_snippet/pdf/python_common_code_snippet.pdf"de_snippet.pdf"}}}},,"title""title"::"Python"Python常⽤代码段常⽤代码段""}}

bookJsonbookJson==recursiveMergeDictrecursiveMergeDict((templateJsontemplateJson,,copycopy..deepcopydeepcopy((currentJsoncurrentJson))))

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

dict字典

129

Page 130: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

list列表和set集合

listvsset

set适⽤于检测某元素是否在集合内、对集合进⾏⼀定的数学操作

不⽀持indexing,slicinglist

普通的数组

⽀持indexing,slicing

把list换成set

someSetsomeSet==setset(([[]]))forforeachItemeachItemininsomeListsomeList::someSetsomeSet..addadd((eachItemeachItem))

set集合转换为字符串

someSetStrsomeSetStr==","","..joinjoin((someSetsomeSet))

把列表转为python正则中的group中可能出现的选项

defdeflistToPatternGrouplistToPatternGroup((curListcurList))::"""Convertlisttopatterngroup""""""Convertlisttopatterngroup"""patternGroupListpatternGroupList==listlist((mapmap((lambdalambdacurTypecurType::"(%s)""(%s)"%%curTypecurType,,curListcurList))))#['(aaa)','(#['(aaa)','(bbb)','(ccc)','(zzz)','(eee)','(yyy)','(ddd)','(xxx)']bbb)','(ccc)','(zzz)','(eee)','(yyy)','(ddd)','(xxx)']groupPgroupP=="|""|"..joinjoin((patternGroupListpatternGroupList))#'(aaa)|(bbb)|(ccc)|(zzz)|(eee)|(yyy)|(ddd)|(xxx)'#'(aaa)|(bbb)|(ccc)|(zzz)|(eee)|(yyy)|(ddd)|(xxx)'

returnreturngroupPgroupP

调⽤:

ValidPlatformTypeListValidPlatformTypeList==[["iOS""iOS",,"Android""Android"]]ValidPlatformRuleValidPlatformRule==listToPatternGrouplistToPatternGroup((ValidPlatformTypeListValidPlatformTypeList))#'(iOS)|(Android)'#'(iOS)|(Android)'

⽬的是⽤于后续的正则判断

TaskFilenamePatternTaskFilenamePattern=="(?P<taskDate>\d+)_(?P<businessType>%s)_(?P<taskName>[a-zA-Z\d]+)_(?"(?P<taskDate>\d+)_(?P<businessType>%s)_(?P<taskName>[a-zA-Z\d]+)_(?P<crawlerType>%s)(_(?P<platform>%s))?"P<crawlerType>%s)(_(?P<platform>%s))?"%%((ValidBusinessTypeRuleValidBusinessTypeRule,,ValidCrawlerTypeRuleValidCrawlerTypeRule,,ValVal

list列表和set集合

130

Page 131: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

idPlatformRuleidPlatformRule))

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2021-01-1621:40:56

list列表和set集合

131

Page 132: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

sort排序

详⻅:

https://github.com/crifan/crifanLibPython/blob/master/crifanLib/crifanDict.pyhttps://github.com/crifan/crifanLibPython/blob/master/crifanLib/demo/crifanDictDemo.py

对字典根据key去排序

fromfromcollectionscollectionsimportimportOrderedDictOrderedDict

defdefsortDictByKeysortDictByKey((originDictoriginDict))::""""""SortdictbykeySortdictbykey""""""originItemsoriginItems==originDictoriginDict..itemsitems(())sortedOriginItemssortedOriginItems==sortedsorted((originItemsoriginItems))sortedOrderedDictsortedOrderedDict==OrderedDictOrderedDict((sortedOriginItemssortedOriginItems))returnreturnsortedOrderedDictsortedOrderedDict

调⽤:

defdefdemoSortDictByKeydemoSortDictByKey(())::originDictoriginDict=={{"c""c"::"abc""abc",,"a""a"::11,,"b""b"::2222}}printprint(("originDict=%s""originDict=%s"%%originDictoriginDict))#originDict={'c':'abc','a':1,'b':22}#originDict={'c':'abc','a':1,'b':22}sortedOrderedDictsortedOrderedDict==sortDictByKeysortDictByKey((originDictoriginDict))printprint(("sortedOrderedDict=%s""sortedOrderedDict=%s"%%sortedOrderedDictsortedOrderedDict))#sortedOrderedDict=OrderedDict([('a',1),('b',22),('c','abc')])#sortedOrderedDict=OrderedDict([('a',1),('b',22),('c','abc')])

sort和sorted

#Function:Demosorted#Function:Demosorted#mainlyreferofficialdoc:#mainlyreferofficialdoc:##排序指南排序指南—Python3.8.2—Python3.8.2⽂档⽂档

#https://docs.python.org/zh-cn/3/howto/sorting.html#https://docs.python.org/zh-cn/3/howto/sorting.html#Author:CrifanLi#Author:CrifanLi#Update:20200304#Update:20200304

fromfromoperatoroperatorimportimportitemgetteritemgetter,,attrgetterattrgetter

sort排序

132

Page 133: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

printprint(("%s%s%s""%s%s%s"%%(('=''='**4040,,"sort""sort",,'=''='**4040))))

originIntListoriginIntList==[[55,,22,,33,,11,,44]]originIntListoriginIntList..sortsort(())sortedSelfIntListsortedSelfIntList==originIntListoriginIntListprintprint(("sortedSelfIntList=%s""sortedSelfIntList=%s"%%sortedSelfIntListsortedSelfIntList))#sortedSelfIntList=[1,2,3,4,5]#sortedSelfIntList=[1,2,3,4,5]

printprint(("%s%s%s""%s%s%s"%%(('=''='**4040,,"sorted""sorted",,'=''='**4040))))

intListintList==[[55,,22,,33,,11,,44]]sortedIntListsortedIntList==sortedsorted((intListintList))printprint(("sortedIntList=%s""sortedIntList=%s"%%sortedIntListsortedIntList))#sortedIntList=[1,2,3,4,5]#sortedIntList=[1,2,3,4,5]

reversedSortIntListreversedSortIntList==sortedsorted((intListintList,,reversereverse==TrueTrue))printprint(("reversedSortIntList=%s""reversedSortIntList=%s"%%reversedSortIntListreversedSortIntList))#reversedSortIntList=[5,4,3,2,1]#reversedSortIntList=[5,4,3,2,1]

intStrDictintStrDict=={{55::'A''A',,11::'D''D',,22::'B''B',,44::'E''E',,33::'B''B'}}dictSortedIntListdictSortedIntList==sortedsorted((intStrDictintStrDict))printprint(("dictSortedIntList=%s""dictSortedIntList=%s"%%dictSortedIntListdictSortedIntList))#dictSortedIntList=[1,2,3,4,5]#dictSortedIntList=[1,2,3,4,5]

normalStrnormalStr=="CrifanLibestlovelanguageisPython""CrifanLibestlovelanguageisPython"strListstrList==normalStrnormalStr..splitsplit(())printprint(("strList=%s""strList=%s"%%strListstrList))sortedStrListsortedStrList==sortedsorted((strListstrList,,keykey==strstr..lowerlower))printprint(("sortedStrList=%s""sortedStrList=%s"%%sortedStrListsortedStrList))#strList=['Crifan','Li','best','love','language','is','Python']#strList=['Crifan','Li','best','love','language','is','Python']#sortedStrList=['best','Crifan','is','language','Li','love','Python']#sortedStrList=['best','Crifan','is','language','Li','love','Python']

studentTupleListstudentTupleList==[[#name,grade,age#name,grade,age(('Cindy''Cindy',,'A''A',,1515)),,(('Crifan''Crifan',,'B''B',,1212)),,(('Tony''Tony',,'B''B',,1010)),,]]sortedTupleList_lambdasortedTupleList_lambda==sortedsorted((studentTupleListstudentTupleList,,keykey==lambdalambdastudentstudent::studentstudent[[22]]))#[2]is#[2]isageageprintprint(("sortedTupleList_lambda=%s""sortedTupleList_lambda=%s"%%sortedTupleList_lambdasortedTupleList_lambda))#sortedTupleList_lambda=[('Tony','B',10),('Crifan','B',12),('Cindy','A',15)]#sortedTupleList_lambda=[('Tony','B',10),('Crifan','B',12),('Cindy','A',15)]

#sameassinglefunction:#sameassinglefunction:

sort排序

133

Page 134: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

defdefgetStudentAgegetStudentAge((curStudentTuplecurStudentTuple))::returnreturncurStudentTuplecurStudentTuple[[22]]#[2]isage#[2]isagesortedTupleList_singleFunctionsortedTupleList_singleFunction==sortedsorted((studentTupleListstudentTupleList,,keykey==getStudentAgegetStudentAge))printprint(("sortedTupleList_singleFunction=%s""sortedTupleList_singleFunction=%s"%%sortedTupleList_singleFunctionsortedTupleList_singleFunction))#sortedTupleList_singleFunction=[('Tony','B',10),('Crifan','B',12),('Cindy','A',1#sortedTupleList_singleFunction=[('Tony','B',10),('Crifan','B',12),('Cindy','A',15)]5)]

#sameasoperatoritemgetter:#sameasoperatoritemgetter:sortedTupleList_operatorsortedTupleList_operator==sortedsorted((studentTupleListstudentTupleList,,keykey==itemgetteritemgetter((22))))printprint(("sortedTupleList_operator=%s""sortedTupleList_operator=%s"%%sortedTupleList_operatorsortedTupleList_operator))#sortedTupleList_operator=[('Tony','B',10),('Crifan','B',12),('Cindy','A',15)]#sortedTupleList_operator=[('Tony','B',10),('Crifan','B',12),('Cindy','A',15)]

classclassStudentStudent::defdef__init____init__((selfself,,namename,,gradegrade,,ageage))::selfself..namename==namenameselfself..gradegrade==gradegradeselfself..ageage==ageagedefdef__repr____repr__((selfself))::returnreturnreprrepr((((selfself..namename,,selfself..gradegrade,,selfself..ageage))))

studentObjectListstudentObjectList==[[StudentStudent(('john''john',,'A''A',,1515)),,StudentStudent(('jane''jane',,'A''A',,1515)),,StudentStudent(('dave''dave',,'A''A',,1515)),,]]sortedObjectListsortedObjectList==sortedsorted((studentObjectListstudentObjectList,,keykey==lambdalambdastudentstudent::studentstudent..ageage))printprint(("sortedObjectList=%s""sortedObjectList=%s"%%sortedObjectListsortedObjectList))#sortedObjectList=[('john','A',15),('jane','A',15),('dave','A',15)]#sortedObjectList=[('john','A',15),('jane','A',15),('dave','A',15)]

#sameasoperatorattrgetter:#sameasoperatorattrgetter:sortedObjectList_operatorsortedObjectList_operator==sortedsorted((sortedObjectListsortedObjectList,,keykey==attrgetterattrgetter(('age''age'))))printprint(("sortedObjectList_operator=%s""sortedObjectList_operator=%s"%%sortedObjectList_operatorsortedObjectList_operator))#sortedObjectList_operator=[('john','A',15),('jane','A',15),('dave','A',15)]#sortedObjectList_operator=[('john','A',15),('jane','A',15),('dave','A',15)]

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

sort排序

134

Page 135: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

enum枚举

枚举基本⽤法

枚举定义

举例1:

fromfromenumenumimportimportEnumEnum

classclassBatteryStateBatteryState((EnumEnum))::UnknownUnknown==00UnpluggedUnplugged==11ChargingCharging==22FullFull==33

举例2:

importimportenumenum

classclassScreenshotQualityScreenshotQuality((enumenum..EnumEnum))::OriginalOriginal==00MediumMedium==11LowLow==22

举例3:

classclassSentenceInvalidReasonSentenceInvalidReason((EnumEnum))::NONENONE=="none""none"UNKNOWNUNKNOWN=="unknown""unknown"EMPTYEMPTY=="empty"emptyTOO_SHORTTOO_SHORT=="tooshort""tooshort"TOO_LONGTOO_LONG=="toolong""toolong"TOO_MANY_INVALID_WORDTOO_MANY_INVALID_WORD=="containtoomanyinvalidwords""containtoomanyinvalidwords"

初始化创建枚举值

直接传⼊对应的(此处是int)值即可:

batteryStateIntbatteryStateInt==22curBattryStateEnumcurBattryStateEnum==BatteryStateBatteryState((batteryStateIntbatteryStateInt))

log输出是:

curBattryStateEnumcurBattryStateEnum==BatteryState.ChargingBatteryState.Charging

enum枚举

135

Page 136: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

获取枚举的名称

curBattryStateNamecurBattryStateName==curBattryStateEnumcurBattryStateEnum..namename

输出: 'Charging'

获取枚举的值

curBattryStateValuecurBattryStateValue==curBattryStateEnumcurBattryStateEnum..valuevalue

输出: 2

类似,直接从定义中获取值:

gScreenQualitygScreenQuality==ScreenshotQualityScreenshotQuality..LowLow..valuevalue#2#2

枚举⾼级⽤法

给枚举中添加函数

classclassTipTypeTipType((enumenum..EnumEnum))::NoTipNoTip=="NoTip""NoTip"TenPercentTenPercent=="TenPercent""TenPercent"FifthPercentFifthPercent=="FifthPercent""FifthPercent"TwentyPercentTwentyPercent=="TwentyPercent""TwentyPercent"

#@property#@propertydefdefgetTipPercentgetTipPercent((selfself))::tipPercenttipPercent==0.00.0ififselfself====TipTypeTipType..NoTipNoTip::tipPercenttipPercent==0.00.0elifelifselfself====TipTypeTipType..TenPercentTenPercent::tipPercenttipPercent==0.100.10elifelifselfself====TipTypeTipType..FifthPercentFifthPercent::tipPercenttipPercent==0.150.15elifelifselfself====TipTypeTipType..TwentyPercentTwentyPercent::tipPercenttipPercent==0.200.20gLoggLog..debugdebug(("self=%s->tipPercent=%s""self=%s->tipPercent=%s",,selfself,,tipPercenttipPercent))returnreturntipPercenttipPercent

调⽤:

tipPercenttipPercent==initiatorTipTypeinitiatorTipType..getTipPercentgetTipPercent(())#tipPercent=0.1#tipPercent=0.1

enum枚举

136

Page 137: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

注意事项

字符串枚举定义最后不要加逗号

enum定义期间不要加(多余的)逗号:

classclassScreenshotQualityScreenshotQuality((enumenum..EnumEnum))::OriginalOriginal==00,,MediumMedium==11,,LowLow==22,,

否则 value就是 tuple元祖了:

gScreenQualitygScreenQuality==ScreenshotQualityScreenshotQuality..LowLow..valuevalue##实际上是实际上是(2,)(2,)printprint(("gScreenQuality=%s""gScreenQuality=%s"%%gScreenQualitygScreenQuality))#gScreenQuality=2#gScreenQuality=2printprint(("type(gScreenQuality)=%s""type(gScreenQuality)=%s"%%typetype((gScreenQualitygScreenQuality))))#type(gScreenQuality)=<class'tup#type(gScreenQuality)=<class'tuple'>le'>

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

enum枚举

137

Page 138: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

collections集合

根据官⽹:

collections---容器数据类型—Python3.8.1⽂档

介绍,集合有很多种,列出供了解:

namedtuple():创建命名元组⼦类的⼯⼚函数

deque:类似列表(list)的容器,实现了在两端快速添加(append)和弹出(pop)ChainMap:类似字典(dict)的容器类,将多个映射集合到⼀个视图⾥⾯

Counter:字典的⼦类,提供了可哈希对象的计数功能

OrderedDict:字典的⼦类,保存了他们被添加的顺序

defaultdict:字典的⼦类,提供了⼀个⼯⼚函数,为字典查询提供⼀个默认值

UserDict:封装了字典对象,简化了字典⼦类化

UserList:封装了列表对象,简化了列表⼦类化

UserString:封装了列表对象,简化了字符串⼦类化

待以后⽤到了,再详细总结。

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:14

collections集合

138

Page 139: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

附录

下⾯列出相关参考资料。

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:13

附录

139

Page 140: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

参考资料

【已解决】AppStore⾃动安装iOS的app:逻辑优化加等待和多试⼏次

【已解决】Python中如何实现函数调⽤时多个可变数量的参数传递

【已解决】Python中如何合并2个dict字典变量的值

【已解决】Python中给Mac中⽂件加上可执⾏权限

【已解决】Python如何从⼆进制数据中⽣成Pillow的Image【已解决】Python的Pillow如何从⼆进制数据中读取图像数据

【已解决】Python的requests中如何下载⼆进制数据保存为图⽚⽂件

【已解决】Python中⽤Pillow去缩⼩分辨率以及保持画质同时最⼤程度压缩图⽚

【已解决】Python中实现⼆进制数据的图⽚的压缩

【已解决】Python中如何解析mp3等⾳频⽂件得到时⻓信息

【已解决】⽤Python代码从视频中提取出⾳频mp3⽂件

【已解决】Python3中通过⼆进制⽣成⽂件类型对象

【已解决】⽤ffmpeg从mp4视频中提取出整个mp3以及根据时间段去分割mp3【已解决】python中从⽂件名后缀推断出MIME类型

【已解决】Python中从int值⽣成Enum枚举和获取枚举值的字符串或名字

【未解决】python的wda中调整appium的settings参数实现功能优化

【已解决】Python中实现类似touch创建⼀个空⽂件

【已解决】Python中根据key去对字典排序

【已解决】Python3中如何把字符串str转换成字节码bytes【已解决】Python的md5运⾏出错:发⽣异常AttributeErrorbuiltin_function_or_methodobjecthasnoattributenew【已解决】Python3中md5报错:Unicode-objectsmustbeencodedbeforehashing【已解决】Python3中判断变量类型

【已解决】Python中删除字典dict中的键值

【已解决】Python中获取⽂件最后更新时间

【已解决】Python中获取OrderedDict中最后⼀个元素

【已解决】python中判断单个或多个单词是否是全部⼩写或⾸字⺟⼩写

【已解决】Python中如何让Enum的字符串输出字段的值⽽不带类型的前缀–在路上

【已解决】Python中给枚举添加内置函数或属性

【基本解决】Python中把wma、wav等格式⾳频转换为mp3–在路上

【已解决】Python中如何格式化⼤⼩为⼈类易读的效果

【已解决】Python中获取带毫秒的时间戳

【已解决】Python中实现dict的递归的合并更新

【已解决】Python中把list换成set【整理】python中⼀次性创建多级⽂件夹,判断⼀个⽂件夹是否已经存在–在路上

【已解决】Python中如何递归的删除整个⾮空⽂件夹–在路上

python-Correctwaytowritelinetofile?-StackOverflowHowdoyoudoasimple"chmod+x"fromwithinpython?-StackOverflow

参考资料

140

Page 141: Python Ä - book.crifan.com · crifan/python_common_code_snippet: Python ²iĶ ¡º² GitbookðÄK°zUü ¼& ày crifan/gitbook_template: demo how to use crifan gitbook template

io.BytesIO.getvalue排序指南—Python3.8.2⽂档

Python常⽤指引—Python3.8.2⽂档

Built-inFunctions—Python3.8.2documentationoperator—Standardoperatorsasfunctions—Python3.8.2documentationPython常⽤指引—Python3.8.2⽂档

3.8.2Documentation编程常⻅问题—Python3.8.2⽂档

术语对照表—Python3.8.2⽂档

enum—Supportforenumerations—Python3.8.2documentationenum---对枚举的⽀持—Python3.9.0a4⽂档

collections---容器数据类型—Python3.8.1⽂档

md5notsupportinpython3.6anddjango1.10-StackOverflowlist-Python:howtojoinentriesinasetintoonestring?-StackOverflow

crifan.com,使⽤署名4.0国际(CCBY4.0)协议发布allrightreserved,poweredbyGitbook最后更

新:2020-08-0910:22:13

参考资料

141