python实例(一)
生活随笔
收集整理的這篇文章主要介紹了
python实例(一)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
寫在前面
開發(fā)工具:pycharm
python 版本:2.7
需求:將很多的wav或pcm文件,通過給定的網(wǎng)址,進(jìn)行語義解析,然后將結(jié)果按照指定的json格式進(jìn)行保存輸出,可以的話考慮性能,比方說給定1萬個(gè)文件的情況。
需要導(dǎo)入的模塊
import os #json相關(guān) import json #線程池 import threadpool #請求相關(guān) import requests #正則相關(guān) import re#聲明的全局變量 filesResult = [] threadPollCount = 10 resultJsonData = [] 復(fù)制代碼文件遍歷
def showFileTree(path):for root, dirs, files in os.walk(path, topdown=False):print "root", to_unicode(root)print "dir", dirs# addFilePath(to_unicode(root), files, "wav|pcm")# filterFile(to_unicode(root),files,"wav")# filesResult.append(files) 復(fù)制代碼正則匹配
def addFilePath(rootpath, files, postfix):for file in files:# print rootpath+os.path.sep + filepattern = re.compile(postfix)if pattern.findall(file):filesResult.append(rootpath + os.path.sep + file) 復(fù)制代碼多線程請求
線程池不懂用法看這里
def startThreadPool(filesPath):# filesPath 應(yīng)該是一個(gè)集合,文件路徑的集合# 我需要做的是將文件路徑取出來,放到每一個(gè)線程池所需要的參數(shù)里面file_list = []for file in filesResult:temp = ([file], None)file_list.append(temp)pool = threadpool.ThreadPool(threadPollCount) # 相當(dāng)于創(chuàng)建線程# makeRequests參數(shù)的含義:第一個(gè)參數(shù)為目標(biāo)函數(shù)為線程需要執(zhí)行的具體函數(shù),# 第二個(gè)參數(shù)為集合,其中里面存放list和map,第一個(gè)為list,第二個(gè)為map,表明第一個(gè)參數(shù)需要用到的參數(shù),比方說這里requestNet函數(shù)需要一個(gè)參數(shù)requestss = threadpool.makeRequests(requestNet, file_list) #相當(dāng)于是將線程池與調(diào)用的函數(shù)相綁定,[pool.putRequest(req) for req in requestss]pool.wait() 復(fù)制代碼request請求
def requestNet(file):url = "http://48.haitou.cc:50080/asr-test/recognize"files = {'audioData': open(file, 'rb')}res = requests.post(url, files=files)showJsonData(file, res.text)#這里注意是res.text從而獲取到返回的內(nèi)容 復(fù)制代碼json解析
#json格式{"state": "OK", "code": 0, "result": {"text": "小杜小杜", "code": 1}} def showJsonData(filepath, res):text = json.loads(res)# print to_unicode(filepath + "對應(yīng)的結(jié)果是:"),print filepath,print "對應(yīng)的結(jié)果是:",err = 0if text['state'] == "OK":print text['result']['text']err = 0;else:print text['state']err = -1#保存數(shù)據(jù)# 需要 進(jìn)行裁剪resultFile = filepath[filepath.rindex("\\")+1:]jsonResult = {"mText": to_unicode(text['result']['text']).encode("utf-8"),"fileName": to_unicode(resultFile).encode("utf-8"),"errCode": err,"engineName": "引擎名稱"}resultJsonData.append(jsonResult) 復(fù)制代碼json寫入文件
def writeData(data):# {# "mText": 識(shí)別結(jié)果,# "fileName": 處理的音頻的名字,# "errCode": 錯(cuò)誤碼,# "engineName": 引擎的名字# }# 寫文件resultFile = open(resultFileName, 'w') #每次都會(huì)覆蓋之前的文件json_str = json.dumps(data,ensure_ascii=False) #這里注意ensure_ascii =Flaseprint json_strresultFile.write(json_str)resultFile.close() 復(fù)制代碼字符編碼
def to_unicode(string):if isinstance(string, unicode):return stringtry:string_uni = string.decode("UTF-8")return string_uniexcept UnicodeDecodeError:pass 復(fù)制代碼執(zhí)行
def main():# wavSrcPath = raw_input("target:")# print wavSrcPathwavSrcPath = "C:\\Users\\telen\\Desktop\\python腳本"showFileTree(to_unicode(wavSrcPath))# print "+++++++++++++++++"# showFile(filesResult)startThreadPool(filesResult)writeData(resultJsonData) 復(fù)制代碼FAQ
pip install threadpool
python "D:\Program Files\python2.7\Lib\requests-2.4.3\setup.py" install 找到相應(yīng)的setup.py 即可安裝,有了這個(gè)之后我終于知道怎么用github上面的python項(xiàng)目了。原來都有setup.py 只要找到相應(yīng)的setup.py就可以用了。 表示我以前真的不知道,怎么用github上面的項(xiàng)目到自己的工程里面。
轉(zhuǎn)載于:https://juejin.im/post/5c98967c6fb9a070d8782fd7
總結(jié)
以上是生活随笔為你收集整理的python实例(一)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Kubernetes日志分析利器:Ela
- 下一篇: 【GitLab】gitlab上配置web