Created
June 27, 2024 00:22
-
-
Save luojiyin1987/15e5084b55e2549d43910e7bc58c2b66 to your computer and use it in GitHub Desktop.
[descriptions](url) to [descriptions][number]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| import re | |
| def convert_markdown_links(input_file, output_file): | |
| """读取 Markdown 文件,将链接转换为脚注形式,并输出到新文件。""" | |
| links = {} | |
| count = 1 | |
| def replace_link(match): | |
| nonlocal count | |
| link_text = match.group(1) | |
| link_url = match.group(2) | |
| if link_url not in links: | |
| links[link_url] = count | |
| count += 1 | |
| return f"[{link_text}][{links[link_url]}]" | |
| with open(input_file, 'r', encoding='utf-8') as infile, \ | |
| open(output_file, 'w', encoding='utf-8') as outfile: | |
| for line in infile: | |
| # 使用正则表达式替换链接 | |
| converted_line = re.sub(r"\[(.*?)\]\((.*?)\)", replace_link, line) | |
| outfile.write(converted_line) | |
| # 在文件末尾添加脚注 | |
| if links: | |
| outfile.write("\n") | |
| for link_url, index in links.items(): | |
| outfile.write(f"[{index}]: {link_url}\n") | |
| if __name__ == "__main__": | |
| while True: | |
| input_file = input("请输入 Markdown 文件名 (或输入 'q' 退出): ") | |
| if input_file.lower() == 'q': | |
| break | |
| if not os.path.isfile(input_file): | |
| print("文件不存在,请重新输入。") | |
| continue | |
| output_file = f"{os.path.splitext(input_file)[0]}_converted.md" | |
| convert_markdown_links(input_file, output_file) | |
| print(f"已将转换后的 Markdown 内容写入到 {output_file}") | |
| break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment