python解决js文件utf-8编码乱码问题


本文摘自php中文网,作者不言,侵删。

这篇文章主要介绍了python解决js文件utf-8编码乱码问题,非常不错,具有参考借鉴价值,需要的朋友可以参考下

html文件中引入js文件,显示乱码!

js文件为utf-8 编码(无bom) ,此时只要将js文件转成utf-8 BOM编码就可以解决了

可以使用notepad++转码

也可以使用下面的python代码批量转码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

# -*- 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解决N阶台阶走法问题的方法

python解决pandas处理缺失值为空字符串的问题

python解决Fedora解压zip时中文乱码的方法

以上就是python解决js文件utf-8编码乱码问题的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python爬虫看哪本书

Python在普通工作中的应用有那些

Python如何批量提取win10锁屏壁纸

Python实现爬取微博热搜存入mysql

Python怎么画直线

Python64位和32位区别

如何用Python正则表达式匹配字符串?

Python能代替shell吗

Python刷题用哪个app

利用库fractions模块让Python支持分数类型

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...