一直苦于浏览器收藏的书签太多太乱,而每次手工整理都需要花费大量的时间。于是用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('2.定义书签分类器,根据上一步得到的标签内容列表,进行分类
# the classifier of bookmarksdef 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 = 'n' + 'n' + 'Bookmarks n' + 'Bookmarksn' + '
' + type_dict_reverse[i] + 'nt
- ' + j[1] + 'n' group += one group += 't
n' for j in item: one = 'tt
n' group += '
n' for i, item in enumerate(link_list_new): group += 't
n' f_new.write(group)
4.使用的库及变量的初始化
import re, json# the bookmarks file exported from your browserhtml = 'bookmarks.html'# the new bookmarks file we want to gethtml_new = 'bookmarks_new.html'# init listlink_list = []
link_list_new = [[] for i in range(6)]# config file of classifiercategory_dict = json.load(open('classify.txt', 'r'))# config file of classifier typetype_dict = json.load(open('classify_type.txt', 'r'))# reverse the dict abovetype_dict_reverse = dict(zip(type_dict.values(), type_dict.keys()))附:读者可以通过修改代码库中的配置文件(classify.txt、classify_type.txt)来自定义分类结果。
作者:八宝粥BBZ
链接:https://www.jianshu.com/p/7041b812e811



