這篇文章給大家分享的是有關python如何實現讀文件保存到字典,修改字典并寫入新文件的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
實例如下所示:
tcode={}
transcode={}
def GetTcode():
#從文本中獲取英文對應的故障碼,并保存在tcode字典(故障碼文本樣例:oxff,0xff,0x00,0x01, "Fuel Volume Regulator Control Circuit High")
with open('text_en.txt','r+')as fileone:
for line in fileone.readlines():
if not line:
continue
line=line.strip()
titems=line.split('\t')
strkey=titems[0].lower()
strtemp=titems[1]
tcode[strkey]=strtemp
def GetTransCode():
#從文本中獲取中文對應的故障碼,并保存在tcode字典(故障碼文本樣例:oxff,0xff,0x00,0x01, "燃油調節器控制電路過高")
with open('text_cn.txt','r+') as fileone:
for line in fileone.readlines():
if not line:
continue
line=line.strip()
transcode[line.split('\t')[0].lower()]=line.split('\t')[1]
def ReplaTransCode():
#將已經翻譯的中文故障碼在英文文本中用ID查找出來并替換,對新的tcode字典key進行排序,并寫入新的文本中
for findkey in transcode.keys():
if tcode.get(findkey,-1)!= -1:
tcode[findkey]=transcode[findkey]
templine=[]
lkeys=tcode.keys()
lkeys.sort()
for key in lkeys:
value=tcode.get(key)
key=key.upper().replace("0X","0x")
templine.append("%s\t%s\n"%(key,value))
with open('text_trans.txt','w+') as filetwo:
filetwo.writelines(templine)
if __name__ == '__main__':
GetTcode()
GetTransCode()
ReplaTransCode()感謝各位的閱讀!關于“python如何實現讀文件保存到字典,修改字典并寫入新文件”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。