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:
This Python script reads multiple .md files, finds duplicate GitHub repos listed within those files, removes them, and displays which repos were removed from which files.
Code
python
import re
import os
def find_github_repos(file_path):
"""Finds GitHub repos in a given .md file."""
try:
with open(file_path, 'r') as file:
content = file.read()
pattern = r'\[(.*?)\]\(https://github\.com/(.*?)\)'
matches = re.findall(pattern, content)
return [(f"https://github.com/{match[1]}", match[0]) for match in matches]
except FileNotFoundError:
print(f"File not found: {file_path}")
return []
def remove_duplicates(repos, file_path):
"""Removes duplicate GitHub repos from a given .md file."""
repo_set = set()
duplicate_repos = set()
for repo, name in repos:
if repo in repo_set:
duplicate_repos.add((repo, name))
else:
repo_set.add(repo)
if duplicate_repos:
with open(file_path, 'r') as file:
lines = file.readlines()
new_lines = []
removed_repos = []
for line in lines:
for repo, name in duplicate_repos:
pattern = rf'- \[{name}\]\({repo}\)'
if re.search(pattern, line):
removed_repos.append((repo, name, file_path))
break
else:
new_lines.append(line)
with open(file_path, 'w') as file:
file.writelines(new_lines)
return removed_repos
return []
def main():
md_files = [file for file in os.listdir('.') if file.endswith('.md')]
all_repos = {}
for file in md_files:
repos = find_github_repos(file)
for repo, name in repos:
if repo not in all_repos:
all_repos[repo] = [(name, file)]
else:
all_repos[repo].append((name, file))
duplicate_repos = {repo: occurrences for repo, occurrences in all_repos.items() if len(occurrences) > 1}
removed_repos = []
for repo, occurrences in duplicate_repos.items():
for name, file in occurrences[1:]:
removed_repos.extend(remove_duplicates([(repo, name)], file))
if removed_repos:
print("Removed duplicate GitHub repos:")
for repo, name, file in removed_repos:
print(f"- [{name}]({repo}) from {file}")
else:
print("No duplicate GitHub repos found.")
if __name__ == "__main__":
main()