用Python處理kindle摘錄的內(nèi)容

不少人都用過(guò)kindle,而且讀到比較在意的內(nèi)容,通常會(huì)錄作筆記。

但是如果你交叉著看不同的書,摘錄全都堆在一個(gè)文件里面了(我的kindle是老版的,不知道新版的是不是這樣)。
不過(guò)好在格式是基本固定的,因此搗鼓一段代碼,作用就是讀取摘錄的文件(一般是My Clippings.txt),
然后分別按書名存放到不同文件中。有興趣的話可以試試。

# -*- coding:utf-8 -*- 
# 把kindle里面的摘錄,按書名分開保存
# by 爾牛   2019-08-15 12:00

import re
from collections import deque
import os

#kindle的摘錄通常格式如下,每?jī)尚?===== 之間的內(nèi)容,固定4行,分別是書名,摘錄的位置和時(shí)間,空行,摘錄或筆記內(nèi)容
'''
==========
鹽鐵往事:兩千年前的貨幣戰(zhàn)爭(zhēng) (史上十大口水戰(zhàn)) (還是定風(fēng)波)
- 您在位置 #184-186的標(biāo)注 | 添加于 2018年4月9日星期一 下午8:10:32

專家最擅長(zhǎng)的事是把用常識(shí)就能判斷的事,用一系列專業(yè)名詞和專業(yè)儀器來(lái)證明你的判斷是錯(cuò)誤的。比如一個(gè)大樓你說(shuō)有問(wèn)題,墻上都裂了大縫了,但專家能拿一個(gè)你從沒(méi)聽過(guò)的理論和一個(gè)你從沒(méi)見過(guò)的儀器證明就是沒(méi)有問(wèn)題,墻上的大縫只是天冷了大樓打了個(gè)噴嚏,過(guò)一會(huì)子就好了。
==========  
'''

def fetch_note(file_path):
    content = deque(maxlen=6)
    with open(file_path,encoding='utf-8') as fp:        
        for line in fp:
            content.append(line.strip())
            #如果content里面有超過(guò)兩行,并且第一個(gè)元素是=====,當(dāng)前行也是=====,說(shuō)明匹配到了一段完整的摘錄
            if len(content) >= 2 and re.match(r'^=+',line) and re.match(r'^=+',content[0]):

                yield content


def write_files(in_file_path,out_file_dir = None): #要讀取的文件路徑,以及輸出文件的目錄
    out_dir = out_file_dir if out_file_dir else os.path.dirname(in_file_path) #如果沒(méi)提供目標(biāo)目錄,則把讀取文件的路徑作為輸出路徑

    if os.path.isfile(out_dir):
        print('目標(biāo)目錄是個(gè)文件,請(qǐng)確認(rèn)!')
        return False
    
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
        
    book_names = {}  #保存文件的引用對(duì)象,格式為{文件名:文件打開的對(duì)象} 即: {file_name : open(file_name,'w') }
    for x in fetch_note(in_file_path):
        book_name,note_time,note_content = x[1],re.sub('^.*?添加于\s+','',x[2]),x[4] #書名、摘錄時(shí)間、摘錄或筆記內(nèi)容
        #print(book_name,note_time,note_content)
        if book_name not in book_names:
            boo_name_full_path = os.path.join(out_dir,book_name) + '.txt' 
            book_name_fp = open(boo_name_full_path,'a',encoding='utf-8') # 用追加模式
            book_names[book_name] = book_name_fp
            
        book_names[book_name].write(note_time + '\n')
        book_names[book_name].write(note_content + '\n\n')
        
    for bk_fp in book_names.values():
        bk_fp.close()
        
    
if __name__ == '__main__':
    file_path = 'D:/My Clippings.txt'
    write_files(file_path)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容