Created
September 5, 2022 14:32
-
-
Save haixinsong/5293cf00be694a10ee0b7c057bba18bc to your computer and use it in GitHub Desktop.
simple file encode trans python tool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from os import listdir | |
| from os import walk | |
| from os.path import isfile,isdir,join | |
| from chardet.universaldetector import UniversalDetector | |
| # may need to `pip3 install chardet` | |
| import codecs | |
| detector = UniversalDetector() | |
| # change the targetPath to your path | |
| targetPath = "test" | |
| tolerantConfidence = 0.8 | |
| careList = [] | |
| def process(filepath,filename): | |
| detector.reset() | |
| with open(filepath,"rb") as filecontent: | |
| for line in filecontent: | |
| detector.feed(line) | |
| if detector.done: break | |
| detector.close() | |
| if detector.result['confidence'] < tolerantConfidence: | |
| careList.append(filepath) | |
| return | |
| if detector.result['encoding'] != 'utf-8': | |
| enc = detector.result['encoding'] | |
| fread = codecs.open(filepath, 'r', enc.upper()) | |
| new_content = fread.read() | |
| codecs.open(filepath,'w',"UTF-8").write(new_content) | |
| print(detector.result, filepath, "converted to utf-8") | |
| for root,dirs,files in walk(targetPath, topdown = False): | |
| for name in files: | |
| process(join(root,name),name) | |
| print ("low confidence, may need recheck: ", careList) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment