TCAX 字幕特效制作工具官方论坛 | ASS | TCAS | Python | Aegisub | Lua

 找回密码
 新人加入
查看: 3277|回复: 0

[其他] Python处理utf-8 添加和删除BOM头 [复制链接]

Rank: 4

发表于 2021-10-7 10:01:17 |显示全部楼层
来源链接:
https://blog.csdn.net/weixin_30621711/article/details/98361204

以下代码只处理了assic和utf8文件。其它文件编码为保险起见并未加入支持。
参数
exts 需要处理文件的扩展名
folders 需要处理的文件夹及子目录
处理目录为当前目录
运行:
添加bom头
python proc_bom.py
删除bom头
python proc_bom.py -r

运行缺少chardet报错 请查看:http://www.cnblogs.com/wangmh/p/8004451.html

  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-

  3. import os;
  4. import sys;
  5. import codecs;
  6. import chardet;

  7. #获取脚本文件的当前路径
  8. def cur_file_dir():
  9.      #获取脚本路径
  10.      path = sys.path[0]
  11.      #判断为脚本文件还是py2exe编译后的文件,如果是脚本文件,则返回的是脚本的目录,如果是py2exe编译后的文件,则返回的是编译后的文件路径
  12.      if os.path.isdir(path):
  13.          return path
  14.      elif os.path.isfile(path):
  15.          return os.path.dirname(path)
  16. #打印结果


  17. #pip install chardet 安装相应插件
  18. def procBOM(strPath,curLen, bAdd):
  19.     newcontent = '';
  20.     f = open(strPath, "rb");
  21.     fcontent = f.read();
  22.     f.close();
  23.     printBuffer = strPath[curLen:]
  24.     codeType = chardet.detect(fcontent)["encoding"]  #检测编码方式  
  25.      printBuffer = printBuffer + "  "+str(codeType)

  26.      if codeType.lower().find('utf-8') == -1 and codeType.lower().find('ascii') == -1 :
  27.          #非utf8文件保险起见先退出,并输出错误提示,todo后续再添加其它转码到utf8
  28.          print printBuffer + " error OK"
  29.          return
  30.    
  31.     #不需要转换,已经添加bom头   

  32.     if bAdd and fcontent[:3] != codecs.BOM_UTF8:
  33.         print  printBuffer+" add bom",
  34.         newcontent = codecs.BOM_UTF8;
  35.         newcontent += fcontent;
  36.     elif not bAdd and fcontent[:3] == codecs.BOM_UTF8:
  37.         newcontent = fcontent[3:];
  38.         print  printBuffer+" del bom",
  39.     else:
  40.         return;
  41.     fnew = open(strPath, "wb+")
  42.     fnew.write(newcontent);
  43.     fnew.close();
  44.     print "done"
  45.     return

  46. if __name__ == "__main__":

  47.     bAdd = True;
  48.     exts = ['.py'];
  49.     folders = ["GNaviInterface/search","src","tester"]
  50.     bAdd = True;
  51.     if(len(sys.argv) > 1 and sys.argv[1] == '-r'):
  52.         bAdd = False;
  53.     curLen = len(cur_file_dir())
  54.     for folderName in folders:
  55.         folderPath = cur_file_dir()+"/"+folderName+"/"
  56.         #print "procBOM:folder path = "+folderPath+",add = "+str(bAdd)
  57.         for parent,dirnames,filenames in os.walk(folderPath):
  58.             for f in filenames:
  59.                 bTargetFile = False;
  60.                 for e in exts:
  61.                     if(f.endswith(e)):
  62.                         bTargetFile = True;
  63.                 if(bTargetFile):
  64.                     procBOM(os.path.join(parent,f),curLen, bAdd);
  65. #print 'file:%s add:%s' % (os.path.join(parent, f), bAdd);
复制代码

转载于:https://www.cnblogs.com/wangmh/p/8005388.html
您需要登录后才可以回帖 登录 | 新人加入

GitHub|TCAX 主页

GMT+8, 2024-3-29 23:23

Powered by Discuz! X2

© 2001-2011 Comsenz Inc.

回顶部
RealH