with io.open(md_file, 'r', encoding='utf-8') as f: #使用utf-8 编码打开 post = f.read() matches = re.compile(img_patten).findall(post) if matches and len(matches)>0 : # 多个group整合成一个列表 for match in list(chain(*matches)) : if match and len(match)>0 : print("match pic : ", match) new_url = match.replace('wangcong.info','babibobi.com')
# 更新MarkDown文件中的URL if new_url : post = post.replace(match, new_url) num_replace = num_replace + 1
# 如果有内容的话,就直接覆盖写入当前的MarkDown文件 if post and num_replace > 0: io.open(md_file, 'w', encoding='utf-8').write(post) print('{0} 中有{1}个URL被替换/{2}'.format(os.path.basename(md_file), num_replace, dir_ts)) elif num_replace == 0: print('{} 中没有需要替换的URL'.format(os.path.basename(md_file)))
if __name__ == '__main__': fileset = os.listdir(sys.argv[1]) for filename in fileset: print filename absfile = os.path.join(sys.argv[1], filename) replace_md_url(absfile)