nicuf

ser

Jul 27th, 2021
958
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from bs4 import BeautifulSoup
  2. from bs4.formatter import HTMLFormatter
  3. import requests
  4. import re
  5. import execjs
  6. from urllib import parse
  7. import json
  8. from collections import Counter
  9.  
  10.  
  11. class UnsortedAttributes(HTMLFormatter):
  12.     def attributes(self, tag):
  13.         for k, v in tag.attrs.items():
  14.             yield k, v
  15.  
  16. files_from_folder = r"c:\Folder2"
  17.  
  18. use_translate_folder = True
  19.  
  20. destination_language = 'fr'
  21.  
  22. ts = Translate_as_google(destination_language)
  23.  
  24. extension_file = ".html"
  25.  
  26. import os
  27.  
  28. directory = os.fsencode(files_from_folder)
  29.  
  30. def recursively_translate(node):
  31.     for x in range(len(node.contents)):
  32.         if isinstance(node.contents[x], str):
  33.             if node.contents[x].strip() != '':
  34.                 try:
  35.                     node.contents[x].replaceWith(ts.translate(node.contents[x]))
  36.                 except Exception as e:
  37.                     print(e)
  38.         elif node.contents[x] != None:
  39.             recursively_translate(node.contents[x])
  40.  
  41. for file in os.listdir(directory):
  42.     filename = os.fsdecode(file)
  43.     print(filename)
  44.  
  45.             for i, file in enumerate(os.listdir(directory)):
  46.                 filename = os.fsdecode(file)
  47.                 print(f"{filename} translated ({i+1})")
  48.  
  49.         soup = soup.encode(formatter=UnsortedAttributes()).decode('utf-8')
  50.         new_filename = f'{filename.split(".")[0]}_{destination_language}.html'
  51.         if use_translate_folder:
  52.             try:
  53.                 with open(os.path.join(files_from_folder+r'\translated', new_filename), 'w', encoding='utf-8') as new_html:
  54.                     new_html.write(soup[5:-6])
  55.             except:
  56.                 os.mkdir(files_from_folder+r'\translated')
  57.                 with open(os.path.join(files_from_folder+r'\translated', new_filename), 'w', encoding='utf-8') as new_html:
  58.                     new_html.write(soup[5:-6])
  59.         else:
  60.             with open(os.path.join(files_from_folder, new_filename), 'w', encoding='utf-8') as html:
  61.                 html.write(soup[5:-6])
  62.  
RAW Paste Data