Python codecs.open方法代碼示例- 純淨天空
文章推薦指數: 80 %
本文整理匯總了Python中codecs.open方法的典型用法代碼示例。
如果您正苦於以下問題:Python codecs.open方法的具體用法?Python codecs.open怎麽用?
當前位置:首頁>>代碼示例>>Python>>正文
本文整理匯總了Python中codecs.open方法的典型用法代碼示例。
如果您正苦於以下問題:Pythoncodecs.open方法的具體用法?Pythoncodecs.open怎麽用?Pythoncodecs.open使用的例子?那麽恭喜您,這裏精選的方法代碼示例或許可以為您提供幫助。
您也可以進一步了解該方法所在類codecs的用法示例。
在下文中一共展示了codecs.open方法的15個代碼示例,這些例子默認根據受歡迎程度排序。
您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Python代碼示例。
示例1:loadWordNet
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportopen[as別名]
defloadWordNet(self):
"""
loadzh_wordnetintotheobject.
將cow-not-full文件中的數據集整合成set
"""
f=codecs.open(self.wordnet_txt,"rb","utf-8")
self.known=dict()
#self.known=set()
forlinf:
ifl.startswith('\ufeff#')ornotl.strip():
continue
row=l.strip().split("\t")
(synset,lemma)=row
#iflen(row)==2:
#(synset,lemma)=row
#eliflen(row)==3:
#(synset,lemma,status)=row#根本就沒有三個東西的項
#else:
#print("illformedline:",l.strip())
#ifnot(synset.strip(),lemma.strip())inself.known:
#self.known.add((synset.strip(),lemma.strip()))
ifnotlemma.strip()inself.known.keys():
self.known[lemma.strip()]=[]
self.known[lemma.strip()].append(synset)開發者ID:Coldog2333,項目名稱:Financial-NLP,代碼行數:26,代碼來源:NLP.py
示例2:txt2sentence
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportopen[as別名]
deftxt2sentence(self,filename):
"""
reada
若不是str類型,則使用默認的停止詞
allow_speech_tags--詞性列表,用於過濾
"""
allow_speech_tags=[util.as_text(item)foriteminallow_speech_tags]
self.default_speech_tag_filter=allow_speech_tags
self.stop_words=set()
self.stop_words_file=get_default_stop_words_file()
iftype(stop_words_file)isstr:
self.stop_words_file=stop_words_file
forwordincodecs.open(self.stop_words_file,'r','utf-8','ignore'):
self.stop_words.add(word.strip())開發者ID:ouprince,項目名稱:text-rank,代碼行數:18,代碼來源:Segmentation.py
示例9:write_to_conll
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportopen[as別名]
defwrite_to_conll(outf,fsp,firstex,sentid):
mode="a"
iffirstex:
mode="w"
withcodecs.open(outf,mode,"utf-8")asoutf:
foriinxrange(fsp.sent.size()):
token,postag,nltkpostag,nltklemma,lu,frm,role=fsp.info_at_idx(i)
outf.write(str(i+1)+"\t")#ID=0
outf.write(token.encode('utf-8')+"\t")#FORM=1
outf.write("_\t"+nltklemma+"\t")#LEMMAPLEMMA=2,3
outf.write(postag+"\t"+nltkpostag+"\t")#POSPPOS=4,5
outf.write(str(sentid-1)+"\t_\t")#FEATPFEAT=6,7~replacingFEATwithsentencenumber
outf.write("_\t_\t")#HEADPHEAD=8,9
outf.write("_\t_\t")#DEPRELPDEPREL=10,11
outf.write(lu+"\t"+frm+"\t")#FILLPREDPRED=12,13
outf.write(role+"\n")#APREDS=14
outf.write("\n")#endofsentence
outf.close()開發者ID:swabhs,項目名稱:open-sesame,代碼行數:23,代碼來源:preprocess.py
示例10:load_data_and_labels
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportopen[as別名]
defload_data_and_labels():
"""
LoadsMRpolaritydatafromfiles,splitsthedataintowordsandgenerateslabels.
Returnssplitsentencesandlabels.
"""
#downloaddataset
get_chinese_text()
#Loaddatafromfiles
positive_examples=list(codecs.open("./data/pos.txt","r","utf-8").readlines())
positive_examples=[s.strip()forsinpositive_examples]
positive_examples=[peforpeinpositive_examplesiflen(pe)<100]
negative_examples=list(codecs.open("./data/neg.txt","r","utf-8").readlines())
negative_examples=[s.strip()forsinnegative_examples]
negative_examples=[neforneinnegative_examplesiflen(ne)<100]
#Splitbywords
x_text=positive_examples+negative_examples
#x_text=[clean_str(sent)forsentinx_text]
x_text=[list(s)forsinx_text]
#Generatelabels
positive_labels=[[0,1]for_inpositive_examples]
negative_labels=[[1,0]for_innegative_examples]
y=np.concatenate([positive_labels,negative_labels],0)
return[x_text,y]開發者ID:awslabs,項目名稱:dynamic-training-with-apache-mxnet-on-aws,代碼行數:27,代碼來源:data_helpers.py
示例11:sendImage
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportopen[as別名]
defsendImage(self,to_,path):
M=Message(to=to_,contentType=1)
M.contentMetadata=None
M.contentPreview=None
M_id=self.Talk.client.sendMessage(0,M).id
files={
'file':open(path,'rb'),
}
params={
'name':'media',
'oid':M_id,
'size':len(open(path,'rb').read()),
'type':'image',
'ver':'1.0',
}
data={
'params':json.dumps(params)
}
r=self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',data=data,files=files)
ifr.status_code!=201:
raiseException('Uploadimagefailure.')
returnTrue開發者ID:CyberTKR,項目名稱:CyberTK-Self,代碼行數:24,代碼來源:Self.py
示例12:sendAudio
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportopen[as別名]
defsendAudio(self,to_,path):
M=Message(to=to_,text=None,contentType=3)
M_id=self.Talk.client.sendMessage(0,M).id
files={
'file':open(path,'rb'),
}
params={
'name':'media',
'oid':M_id,
'size':len(open(path,'rb').read()),
'type':'audio',
'ver':'1.0',
}
data={
'params':json.dumps(params)
}
r=self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',data=data,files=files)
printr
ifr.status_code!=201:
raiseException('Uploadaudiofailure.')開發者ID:CyberTKR,項目名稱:CyberTK-Self,代碼行數:23,代碼來源:Self.py
示例13:sendVoice
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportopen[as別名]
defsendVoice(self,to_,path):
M=Message(to=to_,text=None,contentType=3)
M.contentPreview=None
M_id=self._client.sendMessage(0,M).id
files={
'file':open(path,'rb'),
}
params={
'name':'voice_message',
'oid':M_id,
'size':len(open(path,'rb').read()),
'type':'audio',
'ver':'1.0',
}
data={
'params':json.dumps(params)
}
r=self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',data=data,files=files)
ifr.status_code!=201:
raiseException('Uploadvoicefailure.')
returnTrue開發者ID:CyberTKR,項目名稱:CyberTK-Self,代碼行數:23,代碼來源:Self.py
示例14:bod2darknet
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportopen[as別名]
defbod2darknet(subpath,label,extractclassname):
labelpath=os.path.join(subpath,label)
filelist=GetFileFromThisRootDir(labelpath)
outpath=r'/home/dj/data/bod-subset/labels'
forfullnameinfilelist:
objects=parse_bod_poly(fullname)
name=os.path.splitext(os.path.basename(fullname))[0]
withopen(os.path.join(outpath,name+'.txt'),'w')asf_out:
forobjinobjects:
poly=obj['poly']
bbox=np.array(dots4ToRecC(poly))/1024
if(sum(bbox<=0)+sum(bbox>=1))>=1:
continue
if(obj['name']inextractclassname):
id=extractclassname.index(obj['name'])
else:
continue
outline=str(id)+''+''.join(list(map(str,bbox)))
f_out.write(outline+'\n')開發者ID:ringringyi,項目名稱:DOTA_models,代碼行數:21,代碼來源:utils.py
示例15:bodpolyToRec
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportopen[as別名]
defbodpolyToRec(self,label):
Recpath=os.path.join(self.basepath,r'ReclabelTxt')
forbasenameinself.namelist:
#objects=parse_bod_poly(os.path.join(self.labelpath,basename+'.txt'))
objects=parse_bod_poly(os.path.join(self.basepath,label,basename+'.txt'))
f_out=codecs.open(os.path.join(Recpath,basename+'.txt'),'w','utf_16')
forobjinobjects:
bbox=dots4ToRec8(obj['poly'])
name=obj['name']
difficult=obj['difficult']
bbox=list(map(str,bbox))
outline=''.join(bbox)
outline=outline+''+name
ifdifficult:
outline=outline+''+str(difficult)
f_out.write(outline+'\n')開發者ID:ringringyi,項目名稱:DOTA_models,代碼行數:18,代碼來源:utils.py
注:本文中的codecs.open方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。
延伸文章資訊
- 1Python小坑:open()和codecs.open()区别,以及常见指令和 ...
啥也别说了,用codecs.open()就完事了写贴原因因为接触Python时候已经是Python3.x的年代了,用的文件操作最多的就是with open() as file_:这一段话, ...
- 2python 文件读写时用open还是codecs.open - slower - 博客园
python 文件读写时用open还是codecs.open. 当我面有数据需要保存时,第一时间一般会想到写到一个txt文件中,当然,数据量比较大的时候还是写到数据库 ...
- 3Difference between open and codecs.open in Python
open accepts encoding and newline parameters and interprets them as Python 3 does. Unlike codecs....
- 4codecs — Codec registry and base classes — Python 3.10.7 ...
This module defines base classes for standard Python codecs (encoders and decoders) ... codecs. o...
- 5Python中open和codecs.open之間的區別 - 程式人生
import codecs f = codecs.open(filename, encoding="utf-8") ... 從Python 2.6開始,一種好的做法是使用 io.open() ,...