Advertisement
Guest User

Untitled

a guest
Jan 8th, 2021
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. #!/usr/bin/python3
  2. import os
  3.  
  4. subtitle_dir = r"."
  5.  
  6. """
  7. - Projde rekurzivně daný adresář a hledá soubory s koncovkou *.srt a *.sub.
  8. - Ty se snaží otevřít postupně v kódování windows-1250, utf-8-sig a utf-8.
  9. - Obsah načte (převede do utf-8) a zapíše zpět do původního souboru s
  10.  kódováním utf-8-sig, což je BOM verze.
  11. """
  12.  
  13. def readContent(fn, encodings=['utf-8-sig', 'windows-1250', 'utf-8']):
  14.   for enc in encodings:
  15.     try:
  16.       with open(fn, "rt", encoding=enc) as f:
  17.         return enc, f.readlines()
  18.     except UnicodeDecodeError as e:
  19.       continue
  20.   raise UnicodeDecodeError('Unknown encoding: ' + fn)
  21.  
  22. def writeContent(fn, lines, encoding='utf-8-sig'):
  23.   with open(fn, "wt", encoding=encoding) as f:
  24.     for line in lines:
  25.       f.write(line)
  26.  
  27. # ----------------------------------------------------------------------
  28. # MAIN
  29. # ----------------------------------------------------------------------
  30. if __name__ == '__main__':
  31.   for root, dirs, files in os.walk(subtitle_dir):
  32.     print(f"[{root}]")
  33.     for file in files:
  34.       src = os.path.join(root, file)
  35.       fn, ext = os.path.splitext(src)
  36.       if ext.lower() in (".srt", ".sub"):
  37.         print(f"\t{file}")
  38.         try:
  39.           enc, lines = readContent(src)
  40.           if enc != 'utf-8-sig':
  41.             print(f"\t\tencoding: {enc}")
  42.             writeContent(src, lines, 'utf-8-sig')
  43.         except UnicodeDecodeError as e:
  44.           print("\t\tunknown encoding - unchanged.")
  45.     print()
  46.   input("Press Enter to continue...")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement