Create a Python script that will read multiple .md and find all the duplicate GitHub repos listed within those .md files. It will remove them from those and show in terminal which got remove from which .md file. Github repos in .md are listed like these:
import os
import re
import glob
def extract_github_repos(file_content):
"""Extract GitHub repository URLs from markdown content."""
pattern = r'\[.*?\]\((https://github\.com/[^)]+)\)'
return re.findall(pattern, file_content)
def process_markdown_files(directory='.'):
"""Process all markdown files in the given directory to find and remove duplicate repos."""
# Get all markdown files
md_files = glob.glob(os.path.join(directory, '*.md'))
if not md_files:
print("No markdown files found in the directory.")
return
# Dictionary to track all repositories and their occurrences
all_repos = {}
file_contents = {}
# First pass: collect all repositories and their occurrences
for file_path in md_files:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
file_contents[file_path] = content
repos = extract_github_repos(content)
for repo in repos:
if repo not in all_repos:
all_repos[repo] = []
all_repos[repo].append(file_path)
# Find duplicates (repos that appear in more than one file)
duplicates = {repo: files for repo, files in all_repos.items() if len(files) > 1}
if not duplicates:
print("No duplicate repositories found across the markdown files.")
return
# Second pass: remove duplicates, keeping only the first occurrence
for repo, files in duplicates.items():
# Keep the first file, remove from others
keep_file = files[0]
remove_files = files[1:]
print(f"Duplicate repository found: {repo}")
print(f" Keeping in: {keep_file}")
for file_path in remove_files:
print(f" Removing from: {file_path}")
# Replace the line containing the repo with an empty string
pattern = r'- \[.*?\]\(' + re.escape(repo) + r'\)[^\n]*\n?'
file_contents[file_path] = re.sub(pattern, '', file_contents[file_path])
# Write the modified contents back to the files
for file_path, content in file_contents.items():
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)
print("\nDuplicate repositories have been removed successfully.")
if __name__ == "__main__":
process_markdown_files()
Would you like me to explain or break down this code?