聆听风声 点点滴滴都很珍贵!

使用python把typecho文章导出成jekyll博客md文件

2021-10-18

import re
import pymysql
from string import Template
import html2text

def create_file(file_name,content):
    f = open(file_name,'wt',encoding='utf-8')
    f.writelines(content)
    f.close()
    print('ok')

def create_md(file_name,title,text,created,categorys,tags):
    content = """---
layout: post
title: ${title}
date: ${created}
categories: ${categorys}
tags: ${tags}
excerpt: ${excerpt}
comment: true
---

* content
{:toc}

${text}
    """
    c = Template(content)
    #清除所有标签,正则匹配所有标签。
    excerpt = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])","",text)
    reg1 = re.match('<!--markdown-->',text)
    t = None
    if reg1:
        t = text.replace('\n', '')
        cc = c.safe_substitute(title=title.strip(),created=created.strip(),categorys=categorys.strip(),tags=tags.strip(),excerpt=excerpt[0:200],text=t)
    else:
        t = html2text.html2text(text)
        cc = c.safe_substitute(title=title.strip(),created=created.strip(),categorys=categorys.strip(),tags=tags.strip(),excerpt=excerpt[0:200],text=t)
    create_file(file_name,cc)
    

# 打开数据库连接
try:
    db = pymysql.connect(host='localhost', user='root', passwd='root123.', port=3306,db='rencaixiu',charset='utf8')
    print('连接成功!')
except:
    print('something wrong!')

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# SQL 查询语句
sql = """
SELECT
	CONCAT( FROM_UNIXTIME( typecho_contents.created, "%Y-%m-%d-" ), '', typecho_contents.cid, '.md' ) AS file,
	typecho_contents.cid,
	typecho_contents.title,
	typecho_contents.text,
	FROM_UNIXTIME( typecho_contents.created, "%Y/%m/%d %H:%i" ) AS created,
	aa.categorys,
	aa.tags 
FROM
	`typecho_contents`
	LEFT JOIN (
	SELECT
		cid,
		GROUP_CONCAT( IF ( m.type = 'tag', m.NAME, '' ) SEPARATOR ' ' ) AS tags,
		GROUP_CONCAT( IF ( m.type = 'category', m.NAME, '' ) SEPARATOR ' ' ) AS categorys 
	FROM
		`typecho_relationships` r
		LEFT JOIN typecho_metas m ON r.mid = m.mid 
	WHERE
		m.`name` NOT IN ( '记录生活', '回忆录', '' ) 
	GROUP BY
		cid 
	ORDER BY
		cid DESC 
	) aa ON typecho_contents.cid = aa.cid 
WHERE
	typecho_contents.cid = aa.cid 
ORDER BY
	typecho_contents.cid DESC
"""
try:
    # 执行SQL语句
    cursor.execute(sql)
    # 获取所有记录列表
    results = cursor.fetchall()
    for row in results:
        file_name = row[0]
        cid = row[1]
        title = row[2]
        text = row[3]
        created = row[4]
        categorys = row[5]
        tags = row[6]
        # 打印结果
        print('数据查询成功!')
        create_md(file_name,title,text,created,categorys,tags)
except:
    print("Error: unable to fetch data")

# 关闭数据库连接
db.close()

Similar Posts

Comments