|
- #!/usr/bin/env python3
- # -*- coding: utf-8; mode: python; tab-width: 4; indent-tabs-mode: nil -*-
- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
- #
- # DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
- # Version 2, December 2004
- #
- # Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
- #
- # Everyone is permitted to copy and distribute verbatim or modified
- # copies of this license document, and changing it is allowed as long
- # as the name is changed.
- #
- # DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
- # TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
- #
- # 0. You just DO WHAT THE FUCK YOU WANT TO.
- #
- # Copyright (c) 2020- donkey <anjingyu_ws@foxmail.com>
-
- import os
- import sys
- import platform
- from chardet import detect as char_detect
-
- def change_encode(file_path: str, des: str='utf-8') -> tuple:
- if not os.path.isfile(file_path):
- return (False, "")
-
- r = os.path.abspath(file_path)
-
- with open(r, 'rb') as f:
- detect_result = char_detect(f.read())
- src = detect_result['encoding'].lower()
-
- # print('编码检测结果: {},概率: {}'.format(src, detect_result['confidence']))
-
- if platform.system():
- if src in ['ascii', 'gb2312']:
- src = 'gb18030'
-
- if src != des:
- with open(r, 'r', encoding=src) as fr:
- text = fr.read()
-
- fwe, ext = os.path.splitext(file_path)
- r = f'{fwe}_{des}{ext}'
- with open(r, 'w', encoding=des) as fw:
- fw.write(text)
-
- return (True, r)
-
- if __name__ == "__main__":
- change_encode(sys.argv[1])
|