Advertisement
nicuf

Python - HTML save <title> as link

Dec 13th, 2023
566
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.52 KB | None | 0 0
  1. from bs4 import BeautifulSoup
  2. from collections import defaultdict
  3. from bs4.formatter import HTMLFormatter
  4. import requests
  5. import re
  6. import execjs
  7. from urllib import parse
  8. import json
  9. import os
  10. from unidecode import unidecode  # Importă unidecode
  11.  
  12. def normalize_title(title):
  13.     # Transliterați titlul pentru a elimina diacriticele și apoi faceți fiecare literă de la început de cuvânt cu majusculă
  14.     return unidecode(title).title()
  15.  
  16. def get_file_hash(file_path):
  17.     with open(file_path, encoding='utf-8') as file:
  18.         file_content = file.read()
  19.         return hash(file_content)
  20.  
  21. def delete_duplicate_files(directory):
  22.     file_hashes = defaultdict(list)
  23.  
  24.     # Group files by their content hash
  25.     for file in os.listdir(directory):
  26.         filename = os.path.join(directory, file)
  27.         if os.path.isfile(filename):
  28.             file_hash = get_file_hash(filename)
  29.             file_hashes[file_hash].append(filename)
  30.  
  31.     # Delete duplicate files
  32.     for _, files in file_hashes.items():
  33.         if len(files) > 1:
  34.             # Remove all but the first file
  35.             for file in files[1:]:
  36.                 os.remove(file)
  37.                 print(f"Deleted duplicate file: {file}")
  38.  
  39.  
  40.  
  41. # Directory-ul în care vrei să aplici căutarea și înlocuirea cu regex
  42. directory = "c:\\Folder-Oana\\extracted\\translated"
  43.  
  44. # Sterge fisierele care au acelasi TITLE si pastreaza varianta fisierului a carui marime este mai mare
  45.  
  46. def delete_duplicate_files_by_title(directory):
  47.     title_to_files = defaultdict(list)
  48.  
  49.     # Group files by their <title> content
  50.     for filename in os.listdir(directory):
  51.         file_path = os.path.join(directory, filename)
  52.         if os.path.isfile(file_path):
  53.             with open(file_path, 'r', encoding='utf-8') as file:
  54.                 file_content = file.read()
  55.                 title_match = re.search(r'<title>(.*?)</title>', file_content, re.DOTALL)
  56.                 if title_match:
  57.                     title = title_match.group(1)
  58.                     title_to_files[title].append(file_path)
  59.  
  60.     # Delete duplicate files for each title
  61.     for title, files in title_to_files.items():
  62.         if len(files) > 1:
  63.             # Find the file with the largest size
  64.             largest_file = max(files, key=lambda f: os.path.getsize(f))
  65.  
  66.             # Remove all but the largest file
  67.             for file in files:
  68.                 if file != largest_file:
  69.                     os.remove(file)
  70.                     print(f"Deleted duplicate file: {file} with title: {title}")
  71.  
  72. # Call the function to delete duplicate files by title
  73. delete_duplicate_files_by_title(directory)
  74.  
  75.  
  76. # Lista cu regex-urile și înlocuirile corespunzătoare
  77. regex_and_replace = [
  78.     (r"\\\\.*$", "", 0),
  79.     (r"\\.*\\$", "", 0),
  80.     (r"\\.*$", "", 0),
  81.     (r"\\\\.*$", "", re.MULTILINE),
  82.     (r"\\.*\\$", "", re.MULTILINE),
  83.     (r"\\.*$", "", re.MULTILINE),
  84.     (r"\u200b", "", re.MULTILINE),
  85.     (r"\u206A|\u206B", "", re.MULTILINE),
  86.     (r'html></p>', 'html" />', re.MULTILINE),
  87.     (r'<p><link rel="canonical"', '<link rel="canonical"', 0),
  88.     (r'<p><p class=', '<p class=', 0),
  89.     (r"<p></p>", "", 0),
  90.     # Adaugă alte regex-uri și înlocuiri aici
  91. ]
  92.  
  93. # Parcurge toate fișierele din director
  94. for filename in os.listdir(directory):
  95.     file_path = os.path.join(directory, filename)
  96.  
  97.     # Verifică dacă este un fișier și obține conținutul
  98.     if os.path.isfile(file_path):
  99.         with open(file_path, 'r', encoding='utf-8') as file:
  100.             file_content = file.read()  # Define 'file_content' for each file
  101.  
  102.             # Găsește conținutul tagului <title>
  103.             title_match = re.search(r'<title>(.*?)</title>', file_content, re.DOTALL)
  104.             if title_match:
  105.                 title = title_match.group(1)
  106.  
  107.                 # Normalizează titlul
  108.                 normalized_title = normalize_title(title)
  109.  
  110.                 # Înlocuiește titlul original cu cel normalizat în conținutul fișierului
  111.                 file_content = file_content.replace(title, normalized_title)
  112.  
  113.                 # Scrie conținutul actualizat înapoi în fișier
  114.                 with open(file_path, 'w', encoding='utf-8') as file:
  115.                     file.write(file_content)
  116.  
  117.         print(f"Procesat fișierul: {filename}")
  118.  
  119. # Call the function to delete duplicate files
  120. delete_duplicate_files(directory)
  121.  
  122.  
  123.  
  124.  
  125.  
  126. class UnsortedAttributes(HTMLFormatter):
  127.     def attributes(self, tag):
  128.         for k, v in tag.attrs.items():
  129.             yield k, v
  130.  
  131.  
  132. def read_text_from_file(file_path):
  133.     """
  134.    Aceasta functie returneaza continutul unui fisier.
  135.    file_path: calea catre fisierul din care vrei sa citesti
  136.    """
  137.     with open(file_path, encoding='utf8') as f:
  138.         text = f.read()
  139.         return text
  140.  
  141. def write_to_file(text, file_path, encoding='utf8'):
  142.     """
  143.    Aceasta functie scrie un text intr-un fisier.
  144.    text: textul pe care vrei sa il scrii
  145.    file_path: calea catre fisierul in care vrei sa scrii
  146.    """
  147.     with open(file_path, 'wb') as f:
  148.         f.write(text.encode('utf-8', 'ignore'))
  149.  
  150. # directory = "c:\\Folder3\\translated"
  151.  
  152. extension_file = ".html"
  153.  
  154. directory = os.fsencode(directory)
  155.  
  156. amount = 1
  157. for file in os.listdir(directory):
  158.     filename = os.fsdecode(file)
  159.     if filename == 'y_key_e479323ce281e459.html' or filename == 'directory.html':
  160.         continue
  161.  
  162.     if filename.endswith(extension_file):
  163.         current_file_name = ''
  164.         new_file_name = ''
  165.  
  166.         with open(os.path.join(directory.decode(), filename), encoding='utf-8') as html:
  167.             file_text = html.read()
  168.             soup = BeautifulSoup('<pre>' + file_text + '</pre>', 'html.parser')
  169.             text_title = soup.findAll('title')[0].get_text()
  170.  
  171.             print(f'{filename} changed filename ({amount})')
  172.             amount += 1
  173.             new_filename = text_title
  174.             # replace 's
  175.             new_filename = re.sub('\'\w', '', new_filename)
  176.             new_filename = new_filename.lower()
  177.             words = re.findall(r'\w+', new_filename)
  178.             new_filename = '-'.join(words)
  179.             new_filename = new_filename + '.html'
  180.             new_filename = os.fsdecode(new_filename)
  181.  
  182.             # Transliterați numele de fișier pentru a elimina diacriticele
  183.             new_filename = unidecode(new_filename)
  184.  
  185.             # inlocuire nume fisier
  186.             current_file_name = os.path.join(directory.decode(), filename)
  187.             new_file_name = os.path.join(directory.decode(), new_filename)
  188.  
  189.             if os.path.exists(new_file_name):
  190.                 # Append a suffix to the new file name
  191.                 base_name, extension = os.path.splitext(new_filename)
  192.                 suffix = 1
  193.                 while os.path.exists(new_file_name):
  194.                     new_filename = f"{base_name}_{suffix}{extension}"
  195.                     new_file_name = os.path.join(directory.decode(), new_filename)
  196.                     suffix += 1
  197.  
  198.             canonical_pattern = re.compile('<link rel="canonical" href="(.*?)>')
  199.             canonical = re.findall(canonical_pattern, file_text)
  200.             if len(canonical) > 0:
  201.                 canonical = canonical[0]
  202.                 link_nou = "https://trinketbox.ro/" + '-'.join(words) + ".html"
  203.                 file_text = file_text.replace(canonical, link_nou)
  204.                 write_to_file(file_text, current_file_name)
  205.             else:
  206.                 print("Nu am gasit tag-ul canonical in fisier")
  207.  
  208.         html.close()
  209.         os.rename(current_file_name, new_file_name)
  210.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement