Created
April 2, 2014 13:11
-
-
Save netwjx/9933779 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 with_statement | |
import os, re | |
reName1 = re.compile(r'^\d+-\d+-\d+_[^\.]+\.markdown$') | |
reName1_1 = re.compile(r'^\d+-\d+-\d+_[^\.]+\.md$') | |
reName2 = re.compile(r'^\d+-\d+-\d+-[^\.]+\.markdown$') | |
reDate = re.compile(r'^date: ([\d\-]+) (\d+):(\d+)\n$', re.I) | |
# 重命名文件,根据文件头部的Date: 2014-01-11 12:11 重命名为 2014-01-11_12-11.md | |
def rename(): | |
for f in os.listdir('.'): | |
if not os.path.isfile(f): | |
continue | |
m = reName1.match(f) | |
if m == None: | |
m = reName2.match(f) | |
if m != None: | |
with open(f) as ff: | |
for line in ff: | |
m2 = reDate.match(line) | |
if m2 != None: | |
newName = '%s_%s-%s.md' % (m2.group(1), m2.group(2), m2.group(3)) | |
print '%s -> %s' % (f, newName) | |
os.rename(f, newName) | |
# 重写文件 | |
# 把文件头部的date: xxxx title: xxxx published:xxx 替换成首字母大写 Date: Title: Published: | |
# categories: xxxx 替换成tags: xxx | |
# 其它的删除 包括--- | |
def rewrite(): | |
import codecs | |
files = (f for f in os.listdir('.') if reName1_1.match(f) != None) | |
fn = 0 | |
for f in tuple(files):#[40:]: | |
# if f != '2012-06-03_14-55.md': | |
# continue | |
lines = [] | |
with codecs.open(f, encoding='utf-8') as ff: | |
ln = 0 | |
for l in ff: | |
ln += 1 | |
if ln > 10: | |
lines.append(l) | |
continue | |
# break | |
ll = re.sub(ur'^-{3,}\r\n$', u'', l) | |
if ll != l: | |
continue | |
ll = re.sub(ur'^layout: [\w\s]+$', u'', l) | |
if ll != l: | |
continue | |
ll = re.sub(ur'^comments: [\w\s]+$', u'', l) | |
if ll != l: | |
continue | |
if ll == l: | |
ll = re.sub(ur'^title: "?([^"]+)"?([\r\n]+)$', ur'Title: \1\2', l) | |
if ll != l: | |
lines.append(ll) | |
if ll == l: | |
ll = re.sub(ur'^date: ([^\r\n]+)([\r\n]+)$', ur'Date: \1\2', l) | |
if ll != l: | |
lines.append(ll) | |
if ll == l: | |
ll = re.sub(ur'^published: ([^\r\n]+)([\r\n]+)$', ur'Published: \1\2', l) | |
if ll != l: | |
lines.append(ll) | |
if ll == l: | |
ll = re.sub(ur'^categories: ([^\r\n]*)([\r\n]+)$', ur'\1', l) | |
if ll != l: | |
ll = u'Tags: %s\r\n' % ', '.join(ll.lower().split(' ')).strip(u', ') | |
lines.append(ll) | |
if ll == l: | |
lines.append(ll) | |
# TODO write | |
# print repr(lines) | |
# print '''%s | |
# %s | |
# ''' % (f.encode('utf-8'), ''.join(lines).encode('utf-8')) | |
with codecs.open('_' + f, 'w', encoding='utf-8') as ff: | |
ff.writelines(lines) | |
if __name__ == '__main__': | |
# rename() | |
rewrite() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment