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

相关文章

pandas.dataframe按行索引表达式选取方法

需要把一个从csv文件里读取来的数据集等距抽样分割,这里用到了列表表达式和dataframe.iloc 先生成索引列表: index_list = ['%d' %i for i in...

django 实现电子支付功能的示例代码

django 实现电子支付功能的示例代码

思路:调用第三方支付 API 接口实现支付功能。本来想用支付宝来实现第三方网站的支付功能的,但是在实际操作中发现支付宝没有 Python 接口,网上虽然有他人二次封装的的 Python...

设置python3为默认python的方法

设置python3为默认python的方法

我们知道在Windows下多版本共存的配置方法就是改可执行文件的名字,配置环境变量。 Linux中的配置原理差不多,思路就是生成软链接,配置到环境变量。 在没配置之前,我的Ubuntu中...

python 图片验证码代码

下面是一个实战项目的结果。 复制代码 代码如下:#coding: utf-8 import Image,ImageDraw,ImageFont,os,string,random,Imag...

python内置模块collections知识点总结

python内置模块collections介绍 collections是Python内建的一个集合模块,提供了许多有用的集合类。 1、namedtuple python提供了很多非常好用...