def add_escape(value): #给mysql无法直接插入的符号添加转移字符 reserved_chars = r'''\"\'''' replace = ['\\' + l for l in reserved_chars] trans = str.maketrans(dict(zip(reserved_chars, replace))) return value.translate(trans)
for file in filenames: result=[] #未处理list num=0 #判断特殊字符奇偶 cut=[] #处理完成包含文章标题和内容的list file = open('python\\'+file, "rb") lines = file.readlines() for item in lines: if (item.decode().startswith('-')) is True: #逐行读取,如果是以 - 开头就跳过不处理 continue else: if (item.decode().startswith('title')) is True: #如果以title开头匹配出文章标题 replace = item.decode().replace("title: ", "") title = replace.strip()#显示结果并去掉空行 result.append(title) elif (item.decode().startswith('date')) is False and (item.decode().startswith('categories')) is False and (item.decode().startswith('tags')) is False : #跳过日期、分类、标签提取文章内容,如果这几个需要也可以单独处理 if (item.decode().startswith(' ```')) is True: #如果匹配到hexo代码高亮 num=num+1 if (num%2) == 0: result.append('') #如果计数器是偶数,添加wordpress代码高亮结束 else: result.append('') #如果计数器是奇数,添加wordpress代码高亮开始 result.append(item.decode()) for item in result : if item != "" and item != "``` \r\n" and item != " ```" and item != "\r\n": #去掉文章中没用的hexo代码高亮、空字符、空行 cut.append(add_escape(item)) #最终处理完的list content_end = "".join(cut[1:]) #提取文章内容 title_end = "".join(cut[0]) #提取标题 con=pymysql.connect(host='us.qingcloud.work',user='*****',password='*****',database='*****',charset='utf8') #连接mysql cur=con.cursor() sql='update wp_posts set post_content = "%s" where post_title = "%s" order by post_content desc;' % (content_end,title_end)#更新文章内容 print (sql) #打印执行的sql cur.execute(sql) all=cur.fetchall() print(all) #执行结果反馈 con.commit() #提交修改 con.close() #关闭数据库连接