python解决js文件utf-8编码乱码问题(推荐)

yipeiwu_com6年前Python基础

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('目录') 

总结

以上所述是小编给大家介绍的python解决js文件utf-8编码乱码问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

python sort、sorted高级排序技巧

Python list内置sort()方法用来排序,也可以用python内置的全局sorted()方法来对可迭代的序列排序生成新的序列。 1)排序基础 简单的升序排序是非常容易的。只需要...

Python实现树莓派WiFi断线自动重连的实例代码

实现 WiFi 断线自动重连。原理是用 Python 监测网络是否断线,如果断线则重启网络服务。 1.Python 代码 autowifi.py,放在 /home/pi 目录下: #...

Python开发的HTTP库requests详解

Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythoner进行网...

Python数据结构与算法之使用队列解决小猫钓鱼问题

Python数据结构与算法之使用队列解决小猫钓鱼问题

本文实例讲述了Python数据结构与算法之使用队列解决小猫钓鱼问题。分享给大家供大家参考,具体如下: 按照《啊哈》里的思路实现这道题目,但是和结果不一样,我自己用一幅牌试了一下,发现是我...

Python数据持久化shelve模块用法分析

本文实例讲述了Python数据持久化shelve模块用法。分享给大家供大家参考,具体如下: 一、简介 在python3中我们使用json或者pickle持久化数据,能dump多次,但只能...