整體思路
- 目標:將Kindle中的每本書的筆記標注單獨提取出保存為一個Markdown文件
其中檢測KIndle是否已經正常插入的判斷方法:
- 思路1:讀取媒介掛載記錄
- 思路2:直接判斷掛載地址是否存在
實現的時候用的第二個思路,Kindle的掛載路徑為/media/當前用戶名/Kindle
,只需判斷這個地址是否存在且能進入正常進行讀取操作即可
其中對於信息提取,My Clippings.txt中內容格式如下
書名 作者
標注/筆記所在位置 時間
空行
筆記/標注內容
==========
每一條筆記都由十個=
號進行分割。這樣就很容易將內容分開了。
代碼實現
#!/usr/bin/env python
# encoding: utf-8
import os
import getpass
class KindleExtract():
def __init__(self):
pass
def kindle_check(self):
"""檢測Kindle的Clippings文件"""
username = getpass.getuser()
kindle_path = ""
try:
if 'Kindle' in os.listdir("/media/"+username):
kindle_path = "/media/"+username+"/Kindle"
print u"檢測到您的Kindle"
else:
print u"未檢測到您的Kindle設備,請確認插入正確再運行本腳本"
exit(1)
if "My Clippings.txt" in os.listdir(kindle_path+"/documents"):
kindle_path = kindle_path+"/documents/My Clippings.txt"
print u"檢測到標注信息所在文件"
else:
print u"未檢測到標注信息文件"
exit(2)
except Exception, e:
print e
return kindle_path
def get_data(self,kindle_path=None):
result ={}
book=[]
item=[]
with open(kindle_path) as f:
for i,cont in enumerate(f.readlines()):
cont = cont.strip()
if "==========" == cont:
book.append(item)
item = []
continue
# if cont != "":
item.append(cont)
caption = []
for i in book:
caption.append(i[0])
caption = set(caption)
tmp ={}
for i in caption:
tmp[i] = []
for i in book:
tmp[i[0]].append(i[3])
for i in tmp:
c = str(i).split(" ")
title = c[0]
print title
author = " ".join(c[1:])
with open(i.replace("/","·")+".md","w") as out_file:
out_file.write("# 書名:《《"+title+"》》\n")
out_file.write("> 作者:《《"+author+"\n")
for id,item in enumerate(tmp[i]):
out_file.write("+ %s%s\n"%(id,item))
if __name__ == "__main__":
ke = KindleExtract()
ke.get_data(kindle_path="clip.txt")
諸多不完善