Advertisement
VanoHa

кодировка

Nov 28th, 2022
771
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.89 KB | None | 0 0
  1. # какой то файл скачанный с интернета в неизвестной кодировке.
  2. open('test.txt', 'w', encoding='cp500').write('Hello\n')
  3.  
  4. # сюда можно впихнуть все известные кодировки.
  5. encoding = [
  6. 'utf-8',
  7. 'cp500',
  8. 'utf-16',
  9. 'GBK',
  10. 'windows-1251',
  11. 'ASCII',
  12. 'US-ASCII',
  13. 'Big5'
  14. ]
  15.  
  16. correct_encoding = ''
  17.  
  18. for enc in encoding:
  19.     try:
  20.         open('test.txt', encoding=enc).read()
  21.     except (UnicodeDecodeError, LookupError):
  22.         pass
  23.     else:
  24.         correct_encoding = enc
  25.         print('Done!')
  26.         break
  27.  
  28.  
  29. print(correct_encoding)
  30.  
  31.  
  32. from chardet.universaldetector import UniversalDetector
  33.  
  34. detector = UniversalDetector()
  35. with open('test.txt', 'rb') as fh:
  36.     for line in fh:
  37.         detector.feed(line)
  38.         if detector.done:
  39.             break
  40.     detector.close()
  41. print(detector.result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement