1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
import os import re import time
def readCSDNInfo(): CSDNInfo = {} with open("CSDN_INFO.txt", "r", encoding="utf-8") as f: title = re.findall(r"title\": \"(.*?)\"", f.read()) f.seek(0) postTime = re.findall(r"postTime\": \"(.*?)\"", f.read()) f.seek(0) all_tags = re.findall(r'"tags":\s*\[([^\]]+)\]', f.read()) tags = [None] * len(title) for tag_group in all_tags: tags[all_tags.index(tag_group)] = re.findall(r'"([^"]+)"', tag_group) for i in range(len(title)): CSDNInfo[title[i]] = {} CSDNInfo[title[i]]["postTime"] = postTime[i] CSDNInfo[title[i]]["tags"] = tags[i] return CSDNInfo
def addInfo2MD(mdPath, CSDNInfo): title = os.path.basename(mdPath).split(".")[0] if title in CSDNInfo: with open(mdPath, "r", encoding="utf-8") as f: lines = f.readlines() if lines[0].startswith("---"): return with open(mdPath, "r", encoding="utf-8") as f: content = f.read() with open(mdPath, "w", encoding="utf-8") as f: f.write("---\n") f.write(f"title: \"{title}\"\n") f.write(f"date: {CSDNInfo[title]['postTime']}\n") f.write(f"tags: {CSDNInfo[title]['tags']}\n") f.write("---\n") f.write(content) print(f"AddInfo: {title}") else: print(f"Error: {title} not in CSDN_INFO.txt")
def traverseMDFiles(mdDir, CSDNInfo): for root, dirs, files in os.walk(mdDir): for file in files: if file.endswith(".md"): mdPath = os.path.join(root, file) addInfo2MD(mdPath, CSDNInfo)
if __name__ == "__main__": mdDir = "md" CSDNInfo = readCSDNInfo() traverseMDFiles(mdDir, CSDNInfo) print("Done!")
|