Pythonで実現したブックマーク分類器

3133 ワード

ブラウザコレクションのブックマークが多すぎて散らかっているのに苦労し、手作業で整理するたびに多くの時間がかかります.そこでPythonでブックマーク分類器を実現し,具体的な過程は以下の通りである.
興味のある学生はGithubに行って完全なコードと関連する配置ファイル(Github転送ドア:bookmarks-classifier)をダウンロードして、運行して、体験してみることができます;コードを修正し、改善し続けることもできます.また、各種pull requestを歓迎し、各種star、forkも歓迎します...
1.ブックマークファイル(HTML形式、ブラウザからエクスポート)を読み込み、正規表現ですべてのAタグ(リンク)の内容を取得する
# read the original bookmarks html, filter the link and text of with open(html, 'r') as f_origin:
lines = re.findall('(.*?)', f_origin.read(), re.S)
print('Total:' + str(len(lines)))
for line in lines:
domain = re.findall('://[a-zA-Z0-9]*\.(.*?)\.', line, re.S)
link = re.findall('HREF="(.*?)"', line, re.S)
text = re.findall('">(.*?)', line, re.S)
        if len(domain) > 0 and len(link) > 0 and len(text) > 0:
            link_item = (domain[0], link[0], text[0])
            link_list.append(link_item)
    print(link_list)
    print('Filter:' + str(len(link_list)))
    classify(link_list)

2.ブックマーク分類器を定義し、前のステップで得たラベル内容リストに基づいて分類する
# the classifier of bookmarks
def classify(list):
    for domain, link, text in list:
        if domain not in category_dict:
            cate = 'other'
        else:
            cate = category_dict[domain]
        link_item_new = (link, text)
        link_list_new[type_dict[cate]].append(link_item_new)
    print(link_list_new)
    print('classify:' + str(len(link_list_new)))

3.前のステップの分類結果を同じ形式のブックマークファイルにエクスポート
# write the results to a new bookmarks html
with open(html_new, 'w') as f_new:
    group = '
' \ + '
' \ + 'Bookmarks
' \ + '

Bookmarks


' \ + '


' for i, item in enumerate(link_list_new): group += '\t

' + type_dict_reverse[i] + '


\t


' for j in item: one = '\t\t

' + j[1] + '
' group += one group += '\t


' group += '


' f_new.write(group)


4.使用するライブラリおよび変数の初期化
import re, json

# the bookmarks file exported from your browser
html = 'bookmarks.html'
# the new bookmarks file we want to get
html_new = 'bookmarks_new.html'
# init list
link_list = []
link_list_new = [[] for i in range(6)]
# config file of classifier
category_dict = json.load(open('classify.txt', 'r'))
# config file of classifier type
type_dict = json.load(open('classify_type.txt', 'r'))
# reverse the dict above
type_dict_reverse = dict(zip(type_dict.values(), type_dict.keys()))

添付:コードライブラリのプロファイル(classify.txt、classify_type.txt)を変更して、分類結果を定義できます.