Last active
August 29, 2015 14:17
-
-
Save hrsano645/6083e6bbc17e3746e59d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
from __future__ import division, print_function, absolute_import, unicode_literals | |
__author__ = 'hiroshi sano<hrs.sano645@gmail.com>' | |
import bs4 | |
import codecs | |
import glob | |
import re | |
import os | |
MD_FILES_DIR = "[SET pelican imported markdown directory path]" | |
WP_XML_FILE = "[SET Wordpress XML file path]" | |
BLOG_BASEURL = "[SET BLOG URL]" | |
MD_TITLE_PATTERN = r"^Title: (.+)$" | |
OUTPUT_DIR_NAME = "output" | |
# xmlのエントリーからsave_asとurlを作る | |
def main(): | |
# bs4でxmlファイルを読み込む | |
with open(WP_XML_FILE) as fstrm_wp_xml: | |
wp_import_xml_raw = fstrm_wp_xml.read() | |
bs_wp_xml = bs4.BeautifulSoup(wp_import_xml_raw, "xml") | |
# ファイルを取り出し、bs4のfind_allで取得したitemを取り出す。 | |
titles_and_urls = [(item.title.get_text(), item.link.get_text()) for item in bs_wp_xml.find_all("item")] | |
# ファイルを保存するディレクトリを作る | |
if not os.path.exists(OUTPUT_DIR_NAME): | |
os.mkdir(OUTPUT_DIR_NAME) | |
output_dir_path = os.path.abspath(OUTPUT_DIR_NAME) | |
print("output dir path : {}".format(output_dir_path)) | |
# フォルダを開いて対象の extension のファイル一覧を作る | |
target_filenames = glob.glob(MD_FILES_DIR) | |
# ファイルを取り出して | |
for md_filename in target_filenames: | |
# ファイルを開いて readlines を取得 | |
with codecs.open(md_filename, encoding="utf-8") as md_file: | |
md_file_readlines = md_file.readlines() | |
# メタデータのタイトルの文字列を取り出す | |
md_meta_title_str = re.findall(MD_TITLE_PATTERN, md_file_readlines[0])[0] | |
# itemsのtitles_and_urlsをループさせて、当てはまるタイトルを探させて、URLを探す | |
for title, url in titles_and_urls: | |
if md_meta_title_str == title: | |
# linkをsave_as, urlのメタデータにするために加工 | |
md_meta_save_as = "Save_as: " + url.replace(BLOG_BASEURL, "") + "index.html\n" | |
md_meta_url = "Url: " + url.replace(BLOG_BASEURL, "") + "\n" | |
md_file_readlines.insert(0, md_meta_save_as) | |
md_file_readlines.insert(1, md_meta_url) | |
print("title match!\ntitle:{} , \n{} , {}".format(title, md_meta_save_as.rstrip(), md_meta_url.rstrip())) | |
# 新しいファイルを生成する。 | |
export_file_path = os.path.join(output_dir_path, os.path.basename(md_filename)) | |
with codecs.open(export_file_path, mode="w", encoding="utf-8") as export_file: | |
export_file.writelines(md_file_readlines) | |
print("export file {}\n".format(export_file_path)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment