Repository navigation
Expand file tree
/
Copy pathaffiliate_links.py
More file actions
43 lines (32 loc) · 1.66 KB
/
Copy pathaffiliate_links.py
File metadata and controls
43 lines (32 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import re
# Define the affiliate ID to append
affiliate_id = "cr2tm-20"
# Prompt the user for the input filename
input_filename = input("Enter the input filename (with extension): ")
# Prompt the user for the output filename
output_filename = input("Enter the output filename (with extension): ")
# Define a regex pattern to find Amazon links
amazon_link_pattern = r"https://www\.amazon\.com/dp/[\w\d]+"
try:
# Read the input file with UTF-8 encoding
with open(input_filename, 'r', encoding='utf-8') as file:
content = file.read()
# Find all Amazon links in the file
amazon_links = re.findall(amazon_link_pattern, content)
# Replace each Amazon link by appending the affiliate tag
for link in amazon_links:
if "?tag=" not in link: # Avoid duplicating the affiliate tag if it already exists
updated_link = f"{link}?tag={affiliate_id}"
content = content.replace(link, updated_link)
# Remove Roman numeral section headings
content = re.sub(r"^\s*[IVXLCDM]+\.\s*", "", content, flags=re.MULTILINE)
# Write the updated content to the output file with UTF-8 encoding
with open(output_filename, 'w', encoding='utf-8') as file:
file.write(content)
print(f"File successfully processed. Updated content saved to: {output_filename}")
except FileNotFoundError:
print(f"Error: The file '{input_filename}' was not found. Please check the filename and try again.")
except UnicodeDecodeError as e:
print(f"Error reading the file: {e}. Ensure the file is encoded in UTF-8 or try specifying the correct encoding.")
except Exception as e:
print(f"An unexpected error occurred: {e}")