python解決js檔案utf-8編碼亂碼問題

來源:互聯網
上載者:User
這篇文章主要介紹了python解決js檔案utf-8編碼亂碼問題,非常不錯,具有參考借鑒價值,需要的朋友可以參考下

html檔案中引入js檔案,顯示亂碼!

js檔案為utf-8 編碼(無bom) ,此時只要將js檔案轉成utf-8 BOM編碼就可以解決了

可以使用notepad++轉碼

也可以使用下面的python代碼批量轉碼

# -*- coding:utf-8 -*- import os,sys import chardet def convert( filename, in_enc = "GBK", out_enc="UTF-8" ):   try:     print("convert " + filename)     f = open(filename,'rb')     content = f.read()     result = chardet.detect(content)#通過chardet.detect擷取當前檔案的編碼格式串,傳回型別為字典類型     print(result)     f.close()     coding = result.get('encoding')#擷取encoding的值[編碼格式]     if coding != 'UTF-8-SIG' and coding == 'utf-8':#檔案格式如果是utf-8的時候,才進行轉碼       print(coding + " to "+ out_enc +"!")       new_content = content.decode(in_enc).encode(out_enc)       f = open(filename, 'wb')       f.write(new_content)       f.close()       print(" done")     else:       print(coding)   except IOError as e:   # except:     print(e) def explore(dir):   for root, dirs, files in os.walk(dir):     for file in files:       path = os.path.join(root, file)       convert(path) def main(dir):   if(os.path.isdir(dir)):     fpaths = [fpath for fpath in os.listdir(dir) if os.path.isfile(dir+"\\"+fpath) and fpath.endswith('.js')]     dpaths = [dpath for dpath in os.listdir(dir) if os.path.isdir(dir+"\\"+dpath)]     for f in fpaths:       convert(dir+"\\"+f,'utf-8','UTF-8-SIG')     for d in dpaths:       print(d)       main(dir+"\\"+d) if __name__ == "__main__":   main('目錄')

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.