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

yipeiwu_com5年前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设计】网站的支持!

相关文章

Python3 replace()函数使用方法

描述 replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。 语法 replace()方法语法: st...

python 调用HBase的简单实例

新来的一个工程师不懂HBase,java不熟,python还行,我建议他那可以考虑用HBase的thrift调用,完成目前的工作。 首先,安装thrift 下载thrift,这里,我用的...

selenium处理元素定位点击无效问题

在WEB自动化测试过程中,经常会遇到这样的问题: 元素定位到了,但是点击无效?有人可能会问了,怎么判断元素定位到了,这个问题很好判断 1.给元素加高亮显示 self.driver...

pycharm远程开发项目的实现步骤

pycharm远程开发项目的实现步骤

你是不是在学习python的时候在使用虚拟机系统进行开发,来回切换很是不方便,那么今天给大家推荐一个pycharm强大的功能。 接下来我们利用这个django项目创建一个子app,测验...

详解Golang 与python中的字符串反转

详解Golang 与python中的字符串反转 在go中,需要用rune来处理,因为涉及到中文或者一些字符ASCII编码大于255的。 func main() { fmt.Pr...