博客园可以直接通过markdown文件导入成博客,我在本地有一些自己的markdown文件,但是里面的图片都是相对路径,其实我将这些文件都打包好传到gitee了,那其实这些图片也在gitee中,所以我只要把markdown文件中的相对路径换成gitee中的路径就好了,下面是我用python写的一个脚本。
import argparse
import os
import re
def replace_string_in_file(source_path, target_path, old_string, new_string):
# 读取源文件
with open(source_path, 'r', encoding='utf-8') as source_file:
content = source_file.read()
# 考虑反斜杠情况
pattern = r'\]\(\..*\)'
matchList = re.findall(pattern, content)
for match in matchList:
newMatch = match.replace('\\', '/')
content = content.replace(match, newMatch)
# 替换url内容
updated_content = content.replace(old_string, new_string)
# 处理新文件名
if (target_path == 'default_target.txt'):
path, filename = os.path.split(source_path)
new_filename = "handled_" + filename
target_path = path + new_filename
# 写入新文件
with open(target_path, 'w', encoding='utf-8') as target_file:
target_file.write(updated_content)
def main():
parser = argparse.ArgumentParser(description='Replace text in a file.')
oldStr = './assets/'
newStr = 'https://gitee.com/zhouyonghao/interview/raw/master/assets/'
# 添加参数
parser.add_argument('-s', '--source', default='default_source.txt', help='Source file path')
parser.add_argument('-t', '--target', default='default_target.txt', help='Target file path')
parser.add_argument('-o', '--old', default=oldStr, help='String to be replaced')
parser.add_argument('-n', '--new', default=newStr, help='Replacement string')
# 解析命令行参数
args = parser.parse_args()
# 调用函数
replace_string_in_file(args.source, args.target, args.old, args.new)
if __name__ == '__main__':
main()
调用方法
$ python3 url_replace.py -s <需要完成替换的文件名>
标签:markdown,target,url,content,source,file,path,替换,string
From: https://www.cnblogs.com/huhudejuhua/p/18299197