一个小工具,PDF的书签

ChongQingJin28 2012-12-03 01:48:31
关于书的格式,只知道html与pdf。

html很容易修改内容,pdf则很容易添加注释!

html更多的是记录详细的东西,有的时候怕一修改,他就不完整了。

所以他更适合做参考。

pdf记录的是零散的知识与智慧,你如果不加上点什么东西的话,恐怕就不能真正的了解他。

或许他才能称之为书!

用python做了一个小工具,可以搜索、查看并打开书签(用pdf阅读器打开)

如果有人能把pdf的内容都转化成一个文档class的话,那他应该用不上这个东西

如果有人不想用PyQt的话,或是其他的如果,那他也不用这个东西

事先的说明:

1.需要PyQt与PDFNetC 及python3

2.如果有exception的话,请自行处理,我并不想做过多的解释,我觉得也没有什么是值得解释的,一切都在源码之中

3.因为我用的是PyQt,所以我也向大家推荐一下PyQt,他就像python一样的容易。只需要一本书就足够了!

共有三个文件:dia是UI。model是工具。main是主文件

凡是“#修改点”注释的地方都是你要修改的地方

代码如下:

文件开始:dia.py

from PyQt4.QtCore import *

from PyQt4.QtGui import *

import sys

_fromUtf8 = lambda s: s

#修改点 为model.mulu = r'D:\Books'的子目录

#应根据你的文件夹做调整

books = ['Python','eclipse','Antlr', 'UML', 'Java', 'Android',

'unix','Web', 'C++','面向对象', '算法']

class Ui_Dialog(object):

''' UI '''

def setupUi(self, Dialog):

Dialog.setObjectName(_fromUtf8("Dialog"))

Dialog.resize(1278, 743)

self.widget = QWidget(Dialog)

self.widget.setGeometry(QRect(4, 16, 1259, 703))

self.widget.setObjectName(_fromUtf8("widget"))

self.horizontalLayout_3 = QHBoxLayout(self.widget)

self.horizontalLayout_3.setMargin(0)

self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))

self.verticalLayout = QVBoxLayout()

self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))

self.horizontalLayout = QHBoxLayout()

self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))

self.label = QLabel(self.widget)

self.label.setObjectName(_fromUtf8("label"))

self.horizontalLayout.addWidget(self.label)

self.lineEdit = QLineEdit(self.widget)

self.lineEdit.setObjectName(_fromUtf8("lineEdit"))

self.horizontalLayout.addWidget(self.lineEdit)

self.verticalLayout.addLayout(self.horizontalLayout)

self.listWidget = QListWidget(self.widget)

self.listWidget.setObjectName(_fromUtf8("listWidget"))

self.verticalLayout.addWidget(self.listWidget)

self.horizontalLayout_3.addLayout(self.verticalLayout)

self.verticalLayout_2 = QVBoxLayout()

self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))

self.horizontalLayout_2 = QHBoxLayout()

self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))

self.label_2 = QLabel(self.widget)

self.label_2.setObjectName(_fromUtf8("label_2"))

self.horizontalLayout_2.addWidget(self.label_2)

self.comboBox = QComboBox(self.widget)

self.comboBox.setObjectName(_fromUtf8("comboBox"))

self.comboBox.setMinimumSize(QSize(221, 16))

global books

for book in books :

self.comboBox.addItem(book)

self.horizontalLayout_2.addWidget(self.comboBox)

spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)

self.horizontalLayout_2.addItem(spacerItem)

self.verticalLayout_2.addLayout(self.horizontalLayout_2)

self.textBrowser = QTreeWidget(self.widget)

self.textBrowser.setFont(QFont("Times", 12))

self.textBrowser.setMinimumSize(QSize(891, 703))

self.textBrowser.setMaximumSize(QSize(891, 703))

self.textBrowser.setObjectName(_fromUtf8("textBrowser"))

#self.highlighter = PythonHighlighter(self.textBrowser.document())

self.verticalLayout_2.addWidget(self.textBrowser)

self.horizontalLayout_3.addLayout(self.verticalLayout_2)

self.retranslateUi(Dialog)

QMetaObject.connectSlotsByName(Dialog)

def retranslateUi(self, Dialog):

Dialog.setWindowTitle(QApplication.translate("Dialog", "Dialog", None, QApplication.UnicodeUTF8))

self.label.setText(QApplication.translate("Dialog", "<html><head/><body><p>Search</p></body></html>", None, QApplication.UnicodeUTF8))

self.label_2.setText(QApplication.translate("Dialog", "Books ", None, QApplication.UnicodeUTF8))


文件结束:dia.py

...全文
441 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
jonsonwang 2014-01-17
  • 打赏
  • 举报
回复
PDFNetC.dll 要放在哪里呢?程序提示找不到DLL模块。
zjs100901 2012-12-06
  • 打赏
  • 举报
回复
引用 6 楼 zhouchongzxc 的回复:
首先再次感谢版主的帮助!! 最近感冒了,身体不是很好,没有及时回帖,还望谅解。 没怎么发过代码,也不知道会出现这样的问题。 把下面代码中的~替换成空格就可以了 ……
你用的浏览器是什么牌子的啊?是不是在发帖框的上方有 17 个图标没法显示啊?如果能显示,请点第 12 个图标,选择弹出的菜单中的 Python,然后在里面,在[code = python]我说的是这里[/code]的里面写你的代码。
冷月清晖 2012-12-05
  • 打赏
  • 举报
回复
引用 2 楼 fibbery 的回复:
有空调调代码格式。
是啊,没法用呢。
y_keven 2012-12-05
  • 打赏
  • 举报
回复
什么东西这是
ChongQingJin28 2012-12-05
  • 打赏
  • 举报
回复
前些天我曾经发帖子说要扩展IDLE,下面是我修改的一段小代码
文件是:EditorWindow.py,函数是:open_module
我想说的是:环境比知识重要。
IDLE本身是一个小型化的eclipse。

~~~~def~open_module(self,~event=None):
~~~~~~~~try:
~~~~~~~~~~~~selected~=~self.text.get("sel.first",~"sel.last")
~~~~~~~~except~TclError:
~~~~~~~~~~~~self.text.bell()
~~~~~~~~~~~~return
~~~~~~~~if~not~selected:
~~~~~~~~~~~~self.text.bell()
~~~~~~~~~~~~return
~~~~~~~~
~~~~~~~~line~=~re.search('line[~:]+(\d+)',selected)
~~~~~~~~if(line):
~~~~~~~~~~~~line~=~int(line.group(1))
~~~~~~~~else:
~~~~~~~~~~~~line~=~re.search('(\d+)',selected)
~~~~~~~~~~~~if(line):
~~~~~~~~~~~~~~~~line~=~int(line.group(1))
~~~~~~~~name~=~re.search(r'[~\\]([a-zA-Z0-9_]+)\.py',selected)
~~~~~~~~if(not~name):
~~~~~~~~~~~~self.text.bell()
~~~~~~~~~~~~return
~~~~~~~~name~=~name.group(1)
~~~~~~~~~~~~

~~~~~~~~try:
~~~~~~~~~~~~(f,~file,~(suffix,~mode,~type_))~=~_find_module(name)
~~~~~~~~except~(NameError,~ImportError)~as~msg:
~~~~~~~~~~~~tkMessageBox.showerror("Import~error",~str(msg),~parent=self.text)
~~~~~~~~~~~~return
~~~~~~~~if~type_~!=~imp.PY_SOURCE:
~~~~~~~~~~~~tkMessageBox.showerror("Unsupported~type",
~~~~~~~~~~~~~~~~"%s~is~not~a~source~module"~%~name,~parent=self.text)
~~~~~~~~~~~~return
~~~~~~~~if~f:
~~~~~~~~~~~~f.close()
~~~~~~~~if~self.flist:
~~~~~~~~~~~~opened~=~self.flist.open(file)
~~~~~~~~~~~~if(line):
~~~~~~~~~~~~~~~~opened.gotoline(line)
~~~~~~~~~~~~
~~~~~~~~else:
~~~~~~~~~~~~opened~=~self.io.loadfile(file)
ChongQingJin28 2012-12-05
  • 打赏
  • 举报
回复
文件开始:dia.py from~PyQt4.QtCore~import~* from~PyQt4.QtGui~import~*~ import~sys _fromUtf8~=~lambda~s:~s #修改点~为model.mulu~=~r'D:\Books'的子目录 #应根据你的文件夹做调整 books~=~['Python','eclipse','Antlr',~'UML',~'Java',~~'Android', ~~~~~~~~'unix','Web',~'C++','面向对象',~'算法'] class~Ui_Dialog(object): ~~~~'''~UI~''' ~~~~def~setupUi(self,~Dialog): ~~~~~~~~Dialog.setObjectName(_fromUtf8("Dialog")) ~~~~~~~~Dialog.resize(1278,~743) ~~~~~~~~self.widget~=~QWidget(Dialog) ~~~~~~~~self.widget.setGeometry(QRect(4,~16,~1259,~703)) ~~~~~~~~self.widget.setObjectName(_fromUtf8("widget")) ~~~~~~~~self.horizontalLayout_3~=~QHBoxLayout(self.widget) ~~~~~~~~self.horizontalLayout_3.setMargin(0) ~~~~~~~~self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3")) ~~~~~~~~self.verticalLayout~=~QVBoxLayout() ~~~~~~~~self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) ~~~~~~~~self.horizontalLayout~=~QHBoxLayout() ~~~~~~~~self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) ~~~~~~~~self.label~=~QLabel(self.widget) ~~~~~~~~self.label.setObjectName(_fromUtf8("label")) ~~~~~~~~self.horizontalLayout.addWidget(self.label) ~~~~~~~~self.lineEdit~=~QLineEdit(self.widget) ~~~~~~~~self.lineEdit.setObjectName(_fromUtf8("lineEdit")) ~~~~~~~~self.horizontalLayout.addWidget(self.lineEdit) ~~~~~~~~self.verticalLayout.addLayout(self.horizontalLayout) ~~~~~~~~self.listWidget~=~QListWidget(self.widget) ~~~~~~~~self.listWidget.setObjectName(_fromUtf8("listWidget")) ~~~~~~~~self.verticalLayout.addWidget(self.listWidget) ~~~~~~~~self.horizontalLayout_3.addLayout(self.verticalLayout) ~~~~~~~~self.verticalLayout_2~=~QVBoxLayout() ~~~~~~~~self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) ~~~~~~~~self.horizontalLayout_2~=~QHBoxLayout() ~~~~~~~~self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) ~~~~~~~~self.label_2~=~QLabel(self.widget) ~~~~~~~~self.label_2.setObjectName(_fromUtf8("label_2")) ~~~~~~~~self.horizontalLayout_2.addWidget(self.label_2) ~~~~~~~~self.comboBox~=~QComboBox(self.widget) ~~~~~~~~self.comboBox.setObjectName(_fromUtf8("comboBox")) ~~~~~~~~self.comboBox.setMinimumSize(QSize(221,~16)) ~~~~~~~~global~books ~~~~~~~~for~book~in~books~: ~~~~~~~~~~~~self.comboBox.addItem(book) ~~~~~~~~self.horizontalLayout_2.addWidget(self.comboBox) ~~~~~~~~spacerItem~=~QSpacerItem(40,~20,~QSizePolicy.Expanding,~QSizePolicy.Minimum) ~~~~~~~~self.horizontalLayout_2.addItem(spacerItem) ~~~~~~~~self.verticalLayout_2.addLayout(self.horizontalLayout_2) ~~~~~~~~ ~~~~~~~~self.textBrowser~=~QTreeWidget(self.widget) ~~~~~~~~self.textBrowser.setFont(QFont("Times",~12)) ~~~~~~~~self.textBrowser.setMinimumSize(QSize(891,~703)) ~~~~~~~~self.textBrowser.setMaximumSize(QSize(891,~703)) ~~~~~~~~self.textBrowser.setObjectName(_fromUtf8("textBrowser")) ~~~~~~~~#self.highlighter~=~PythonHighlighter(self.textBrowser.document()) ~~~~~~~~self.verticalLayout_2.addWidget(self.textBrowser) ~~~~~~~~self.horizontalLayout_3.addLayout(self.verticalLayout_2) ~~~~~~~~self.retranslateUi(Dialog) ~~~~~~~~QMetaObject.connectSlotsByName(Dialog) ~~~~def~retranslateUi(self,~Dialog): ~~~~~~~~Dialog.setWindowTitle(QApplication.translate("Dialog",~"Dialog",~None,~QApplication.UnicodeUTF8)) ~~~~~~~~self.label.setText(QApplication.translate("Dialog",~"<html><head/><body><p>Search</p></body></html>",~None,~QApplication.UnicodeUTF8)) ~~~~~~~~self.label_2.setText(QApplication.translate("Dialog",~"Books~~",~None,~QApplication.UnicodeUTF8)) 文件结束:dia.py 文件开始:model.py import~os~~;import~re import~sys from~PDFNetPython3~import~* from~PyQt4.QtGui~import~* from~PyQt4.QtCore~import~* #修改点 mulu~=~r'D:\Books'~~#一个目录~他的子目录内有pdf文件 ~~~~~~~~ class~xml_content: ~~~~#修改点~python是一个子目录的名称 ~~~~def~__init__(self~,source~=~r'Python'): ~~~~~~~~''' ~~~~~~~~初始化自己的一些东西 ~~~~~~~~''' ~~~~~~~~PDFNet.Initialize() ~~~~~~~~self.source~=~source~~~~#~首先打开的目录 ~~~~~~~~self.pdfdir~=~{}~~~~~~~~#~名称~-->~路径 ~~~~~~~~self.pdfcontent~={}~~~~~#~路径~-->~内容(用于关键字的搜索) ~~~~~~~~self.pdftree_item~={}~~~#~路径~-->~tree_item(用于更新view) ~~~~~~~~self.find_pdf() ~~~~#得到所有的数据~~~~ ~~~~def~get_dir(self): ~~~~~~~~return~self.pdfdir ~~~~ ~~~~def~get_content(self): ~~~~~~~~return~self.pdfcontent ~~~~def~set_path(self,~source):~~~#重新搜索新的路径 ~~~~~~~~'''~重新搜索子文件夹~''' ~~~~~~~~self.source~=~source ~~~~~~~~self.pdfdir~=~{}~~~~~~~ ~~~~~~~~self.find_pdf() ~~~~~~~~ ~~~~#1.2.0~得到书签 ~~~~def~get_book_mark(self~,FirstBookmark): ~~~~~~~~content~=~[] ~~~~~~~~while~FirstBookmark.IsValid(): ~~~~~~~~~~~~indent~=~FirstBookmark.GetIndent()~-~1 ~~~~~~~~~~~~a~=~'~~'~*~indent ~~~~~~~~~~~~content.append(a~+~FirstBookmark.GetTitle()) ~~~~~~~~~~~~if~FirstBookmark.HasChildren():~~~~~~~~ ~~~~~~~~~~~~~~~~content.extend(self.get_book_mark(FirstBookmark.GetFirstChild())) ~~~~~~~~~~~~FirstBookmark~=~FirstBookmark.GetNext() ~~~~~~~~return~content ~~~~#1.2~~寻找pdf内的书签~~~~~~~~~~~ ~~~~def~find_in_pdf(self~,searched): ~~~~~~~~'''得到所有的pdf书签~并保存到pdfcontent中''' ~~~~~~~~self.searched~=~searched ~~~~~~~~if(not~searched): ~~~~~~~~~~~~return~list(self.pdfdir.keys()) ~~~~~~~~finded~=~[] ~~~~~~~~for~file~in~self.pdfdir.keys():~~#在所有的文件之中遍历 ~~~~~~~~~~~~file_path~=~self.pdfdir[file] ~~~~~~~~~~~~if(not~self.pdfcontent.__contains__(file_path)): ~~~~~~~~~~~~~~~~doc~=~PDFDoc(file_path)~~~~#先确定所有的content是存在的 ~~~~~~~~~~~~~~~~doc.InitSecurityHandler() ~~~~~~~~~~~~~~~~root~=~doc.GetFirstBookmark() ~~~~~~~~~~~~~~~~content~=~self.get_book_mark(root~) ~~~~~~~~~~~~~~~~joined~=~'\n'.join(content) ~~~~~~~~~~~~~~~~self.pdfcontent[file_path]~=~joined ~~~~~~~~~~~~~~~~doc.Close() ~~~~~~~~for~file~in~self.pdfdir.keys():~~#在所有的文件之中遍历 ~~~~~~~~~~~~content~=~self.pdfcontent[self.pdfdir[file]] ~~~~~~~~~~~~if(re.search(self.searched,content)): ~~~~~~~~~~~~~~~~finded.append(file) ~~~~~~~~return~finded ~~~~~~~~~~~~~~~~ ~~~~ ~~~~#1.~~在指定的目录中找到所有的pdf文件 ~~~~def~find_pdf(self): ~~~~~~~~global~mulu ~~~~~~~~lists~=~os.listdir(mulu+'\\'+self.source) ~~~~~~~~for~file~in~lists: ~~~~~~~~~~~~full_path~=~mulu+'\\'+self.source+'\\'+file ~~~~~~~~~~~~if(not~os.path.isdir(full_path)~and~full_path.endswith('.pdf')): ~~~~~~~~~~~~~~~~self.pdfdir[file.replace('.pdf','')]~=~full_path ~~~~~~~~ ~~~~~~~~ ~~~~#3.1~添加到widget~~item是书签的item~~parent是Wight或是treeItem ~~~~def~add_to_widget~(self,~item~,~treeWight): ~~~~~~~~item_list~=~[] ~~~~~~~~while~item.IsValid(): ~~~~~~~~~~~~cur_item~=~QTreeWidgetItem(treeWight)~~~~~#建立widgt的顶层目录 ~~~~~~~~~~~~cur_item.setText(0,item.GetTitle())~~~~~~~#设置显示的名字 ~~~~~~~~~~~~cur_item.setData(2,Qt.UserRole,item)~~~~~~#底层数据column~2~ ~~~~~~~~~~~~ ~~~~~~~~~~~~#书签除了goto还能够是什么呢? ~~~~~~~~~~~~action~=~item.GetAction() ~~~~~~~~~~~~if~action.IsValid(): ~~~~~~~~~~~~~~~~if~action.GetType()~==~Action.e_GoTo: ~~~~~~~~~~~~~~~~~~~~dest~=~action.GetDest() ~~~~~~~~~~~~~~~~~~~~if~dest.IsValid(): ~~~~~~~~~~~~~~~~~~~~~~~~page~=~dest.GetPage() ~~~~~~~~~~~~~~~~~~~~~~~~position~=~str(page.GetIndex()) ~~~~~~~~~~~~~~~~~~~~~~~~cur_item.setData(1,Qt.UserRole,position)~~~#设置跳转的页数~column~0~ ~~~~~~~~~~~~else: ~~~~~~~~~~~~~~~~cur_item.setData(1,Qt.UserRole,None)~~~~~~~~~~~~~#设置跳转的页数~为空~~~~~~~~ ~~~~~~~~~~~~item~=~item.GetNext() ~~~~~~~~~~~~item_list.append(cur_item) ~~~~~~~~#广度优先的算法~~先计算所有的子元素,再计算子元素的子元素 ~~~~~~~~for~tree_item~in~item_list: ~~~~~~~~~~~~if~tree_item.data(2,Qt.UserRole).HasChildren(): ~~~~~~~~~~~~~~~~self.add_to_widget(tree_item.data(2,Qt.UserRole).GetFirstChild(),tree_item) ~~~~~~~~if(type(treeWight)~is~QTreeWidget): ~~~~~~~~~~~~treeWight.insertTopLevelItems(0,item_list) ~~~~~~~~~~~~return~item_list ~~~~~~~~else: ~~~~~~~~~~~~treeWight.addChildren(item_list) ~~~~#3.~只显示当前这本书的书签~~~~ ~~~~def~set_viewer(self,book,item_widgt): ~~~~~~~~''' ~~~~~~~~先隐藏掉在treeview中的所有 ~~~~~~~~然后查看是否有已经初始化的treeItem ~~~~~~~~没有则初始化之 ~~~~~~~~显示即可 ~~~~~~~~''' ~~~~~~~~n~=~item_widgt.topLevelItemCount() ~~~~~~~~for~i~in~range(n): ~~~~~~~~~~~~item_widgt.topLevelItem(i).setHidden(True) ~~~~~~~~if(book~in~self.pdftree_item.keys()): ~~~~~~~~~~~~for~item~in~self.pdftree_item[book]: ~~~~~~~~~~~~~~~~item.setHidden(False) ~~~~~~~~else: ~~~~~~~~~~~~doc~=~PDFDoc(book) ~~~~~~~~~~~~doc.InitSecurityHandler() ~~~~~~~~~~~~root~=~doc.GetFirstBookmark()~~#得到第一个书签 ~~~~~~~~~~~~bookMarks~=~self.add_to_widget(root,item_widgt)~~~~#添加所有的书签 ~~~~~~~~~~~~self.pdftree_item[book]~=~bookMarks ~~~~~~~~~~~~doc.Close() ~~~~~~~~~~~~ if~__name__~==~'__main__': ~~~~test~=~xml_content() ~~~~print(test.get_dir()) ~~~~ 文件结束:model.py
ChongQingJin28 2012-12-05
  • 打赏
  • 举报
回复
首先再次感谢版主的帮助!!

最近感冒了,身体不是很好,没有及时回帖,还望谅解。
没怎么发过代码,也不知道会出现这样的问题。


把下面代码中的~替换成空格就可以了

文件开始:main.py
import~os
import~sys
from~PyQt4.QtCore~import~*~
from~PyQt4.QtGui~import~~*
import~dia~;~import~model~;import~sys
import~os~~;~import~re

#修改点~用于打开pdf的程序~要能够接受~-n~参数
pdf_exe~=~r'C:\cygwin\bin\pdf.exe~'

class~myDia(QDialog,dia.Ui_Dialog):
~~~~
~~~~def~__init__(self~):
~~~~~~~~super(myDia,self).__init__()
~~~~~~~~self.setupUi(self)
~~~~~~~~self.search_generator~=~None
~~~~~~~~self.item_list=[]
~~~~~~~~self.init_list()~#1.~创建列表
~~~~~~~~
~~~~~~~~

~~~~#1.~创建列表
~~~~def~init_list(self):
~~~~~~~~self.model~=~model.xml_content()
~~~~~~~~mhash~=~self.model.get_dir()
~~~~~~~~for~aa~in~~mhash.keys():
~~~~~~~~~~~~item~=~QListWidgetItem(aa)
~~~~~~~~~~~~item.setData(1,mhash[aa])
~~~~~~~~~~~~self.item_list.append(item)~~~~#保存所有的item
~~~~~~~~~~~~self.listWidget.addItem(item)
~~~~~~~~self.add_action()~~#1.0~给list添加弹出菜单
~~~~~~~~self.zip_comments~=~self.model.get_content()
~~~~~~~~print('initOk')

~~~~
~~~~#1.0~添加弹出菜单
~~~~def~add_action(self):
~~~~~~~~self.listWidget.setContextMenuPolicy(Qt.ActionsContextMenu)
~~~~~~~~self.textBrowser.setContextMenuPolicy(Qt.ActionsContextMenu)
~~~~~~~~#1.0.0私有方法~~~创建Action
~~~~~~~~run_action~=~self.createAction("Open~pdf",slot~=~self.open_pdf_file)
~~~~~~~~self.listWidget.addAction(run_action)
~~~~~~~~dir_action~=~self.createAction("Open~Dir",slot~=~self.dir_script)
~~~~~~~~self.listWidget.addAction(dir_action)
~~~~~~~~bookmark_action~=~self.createAction("open~Book~Mark",slot~=~self.open_bookmark)
~~~~~~~~self.textBrowser.addAction(bookmark_action)
~~~~~~~~
~~~~~~~~
~~~~#1.0.0私有方法~~~创建Action
~~~~def~createAction(self,~text,~slot=None,~shortcut=None,~icon=None,tip=None,~checkable=False,~signal="triggered()"):
~~~~~~~~action~=~QAction(text,~self)
~~~~~~~~if~icon~is~not~None:
~~~~~~~~~~~~action.setIcon(QIcon("/%s.png"~%~icon))
~~~~~~~~if~shortcut~is~not~None:
~~~~~~~~~~~~action.setShortcut(shortcut)
~~~~~~~~if~tip~is~not~None:
~~~~~~~~~~~~action.setToolTip(tip)
~~~~~~~~~~~~action.setStatusTip(tip)
~~~~~~~~if~slot~is~not~None:
~~~~~~~~~~~~self.connect(action,~SIGNAL(signal),~slot)
~~~~~~~~if~checkable:
~~~~~~~~~~~~action.setCheckable(True)
~~~~~~~~return~action

~~~~#2.0~Action~:~用系统文件打开它就可以了
~~~~def~open_pdf_file(self):
~~~~~~~~global~pdf_exe
~~~~~~~~cur_itm~=~self.listWidget.currentItem()
~~~~~~~~print('the~cur~item~is',cur_itm.data(1))
~~~~~~~~path~=~cur_itm.data(1)
~~~~~~~~os.system(pdf_exe+path)

~~~~#2.0~Action~:~打开所在目录
~~~~def~dir_script(self):
~~~~~~~~cur_itm~=~self.listWidget.currentItem()
~~~~~~~~print('the~cur~item~is',cur_itm.data(1))
~~~~~~~~path~=~cur_itm.data(1)
~~~~~~~~filename~=~re.search(r'(\\[^\\]*?\.pdf)',path).group(1)
~~~~~~~~path~=~path.replace(filename,'')
~~~~~~~~os.system(r'explorer~'+path)

~~~~#打开书签
~~~~def~open_bookmark(self):
~~~~~~~~global~pdf_exe
~~~~~~~~cur_itm~=~self.listWidget.currentItem()
~~~~~~~~print('the~cur~item~is',cur_itm.data(1))
~~~~~~~~path~=~cur_itm.data(1)
~~~~~~~~items~=~self.textBrowser.selectedItems()
~~~~~~~~if(not~items):
~~~~~~~~~~~~return
~~~~~~~~else~:
~~~~~~~~~~~~item~=~items[0]
~~~~~~~~~~~~position~=~str(item.data(1,Qt.UserRole))
~~~~~~~~~~~~print('position',position)
~~~~~~~~~~~~if(position):
~~~~~~~~~~~~~~~~print('go~to~bookmark~',position)
~~~~~~~~~~~~~~~~print(pdf_exe+'"'+path+'"'+'~-n~'+position)
~~~~~~~~~~~~~~~~os.system(pdf_exe+'"'+path+'"'+'~-n~'+position)
~~~~~~~~~~~~else:
~~~~~~~~~~~~~~~~os.system(pdf_exe+path)
~~~~~~~~~~~~~~~~pass
~~~~~~~~~~~~~~~~
~~~~
~~~~#3.0~event~:~根据item的改变而变换信息
~~~~@pyqtSignature("QListWidgetItem~*,QListWidgetItem~*")
~~~~def~on_listWidget_currentItemChanged(self,item_new,item_old):
~~~~~~~~if(item_new~is~None):
~~~~~~~~~~~~return
~~~~~~~~print('the~item~change',item_new.data(1))
~~~~~~~~self.model.set_viewer(item_new.data(1),self.textBrowser)
~~~~~~~~self.on_lineEdit_textChanged(self.lineEdit.text())~~~#同时也将搜索清空
~~~~~~~~
~~~~#3.0~event~:~comboBox的值变化了
~~~~@pyqtSignature("QString")
~~~~def~on_comboBox_currentIndexChanged(self~,string):
~~~~~~~~print('the~item~change',string)
~~~~~~~~self.model.set_path(string)
~~~~~~~~mhash~=~self.model.get_dir()
~~~~~~~~self.listWidget.clear()
~~~~~~~~self.item_list~=~[]
~~~~~~~~for~aa~in~~mhash.keys():
~~~~~~~~~~~~item~=~QListWidgetItem(aa)
~~~~~~~~~~~~item.setData(1,mhash[aa])
~~~~~~~~~~~~self.item_list.append(item)~~~~#保存所有的item
~~~~~~~~~~~~self.listWidget.addItem(item)
~~~~~~~~
~~~~~~~~
~~~~~~~~~~~~
~~~~#双击~其实就是open_pdf_file
~~~~@pyqtSignature("QListWidgetItem~*")
~~~~def~on_listWidget_itemDoubleClicked(self,item_new):
~~~~~~~~#print('the~item~double~clicked',item_new.data(1))
~~~~~~~~self.open_pdf_file()
~~~~
~~~~
~~~~#过滤器~~
~~~~@pyqtSignature("")
~~~~def~on_lineEdit_returnPressed(self):
~~~~~~~~text~=~self.lineEdit.text()
~~~~~~~~search_keys~=~self.model.find_in_pdf(text)
~~~~~~~~finded_item~=~[]
~~~~~~~~for~item~in~self.item_list:
~~~~~~~~~~~~item.setHidden(True)
~~~~~~~~~~~~full_path~=~item.text()
~~~~~~~~~~~~if(full_path~in~search_keys):
~~~~~~~~~~~~~~~~finded_item.append(item)
~~~~~~~~if(finded_item):
~~~~~~~~~~~~for~item~in~finded_item:
~~~~~~~~~~~~~~~~item.setHidden(False)
~~~~~~~~~~~~self.listWidget.setItemSelected(finded_item[0],True)
~~~~~~~~~~~~self.on_listWidget_currentItemChanged(finded_item[0],None)

~~~~#设置要搜索的东西
~~~~@pyqtSignature("QString")
~~~~def~on_lineEdit_textChanged(self~,text):
~~~~~~~~#print('text~chaned~',text)
~~~~~~~~self.searched~=~text
~~~~~~~~self.search_generator~=~None


~~~~#双击事件~
~~~~@pyqtSignature("QTreeWidgetItem~*,int")
~~~~def~on_textBrowser_itemDoubleClicked(self~,item,index):
~~~~~~~~#print('on_textBrowser_itemDoubleClicked',item,index)
~~~~~~~~self.open_bookmark()


~~~~#处理F3
~~~~def~event(self,~event):
~~~~~~~~if~(event.type()~==~QEvent.KeyPress~and
~~~~~~~~~~~~event.key()~==~Qt.Key_F3):
~~~~~~~~~~~~self.search()~~#Action~搜索~(F3)
~~~~~~~~~~~~self.textBrowser.setFocus()
~~~~~~~~~~~~return~True
~~~~~~~~return~QDialog.event(self,~event)

~~~~~~~~
~~~~#Action~搜索~(F3)~main
~~~~def~search(self):
~~~~~~~~self.textBrowser.childCount~=~self.textBrowser.topLevelItemCount
~~~~~~~~self.textBrowser.child~=~self.textBrowser.topLevelItem
~~~~~~~~self.__searched=[]
~~~~~~~~if(not~self.search_generator):
~~~~~~~~~~~~self.search_item(self.textBrowser)
~~~~~~~~~~~~self.search_generator~=~self.search_in()
~~~~~~~~try:
~~~~~~~~~~~~item~=~self.search_generator.__next__()
~~~~~~~~~~~~#print('yousearched~item~',item.text(0))
~~~~~~~~~~~~self.textBrowser.scrollToItem(item)
~~~~~~~~~~~~self.textBrowser.setItemSelected(item,True)
~~~~~~~~except~StopIteration:
~~~~~~~~~~~~self.search_generator~=~None
~~~~~~~~~~~~
~~
~~~~#Action~搜索~~遍历所有的元素~为yield做准备
~~~~def~search_item(self,~parentitem):
~~~~~~~~top_count~=~parentitem.childCount()
~~~~~~~~for~top~in~range(0,top_count):
~~~~~~~~~~~~item~=~parentitem.child(top)
~~~~~~~~~~~~if(re.search(self.searched,item.text(0),flags~=~2)):
~~~~~~~~~~~~~~~~self.__searched.append(item)
~~~~~~~~~~~~if(item.childCount()>0):~~~~#添加所有的书签
~~~~~~~~~~~~~~~~self.search_item(item)
~~~~~~~~

~~~~#Action~搜索~用yield得到已经搜索的
~~~~def~search_in(self,):
~~~~~~~~for~item~in~self.__searched:
~~~~~~~~~~~~yield~item
~~~~~~~~~~~~
def~main(arg~=~None):
~~~~app~=~QApplication(sys.argv)
~~~~form~=~~myDia()
~~~~form.show()
~~~~app.exec_()
~
if~__name__~==~"__main__":
~~~~main()

文件结束:main.py
zjs100901 2012-12-03
  • 打赏
  • 举报
回复
引用 2 楼 fibbery 的回复:
有空调调代码格式。
是啊,对于 Python 来说,没缩进可不是小小的语法错误是可怕的逻辑错误啊 不是没法用是会做错事啊
wwq100 2012-12-03
  • 打赏
  • 举报
回复
支持一个 。
fibbery 2012-12-03
  • 打赏
  • 举报
回复
有空调调代码格式。
ChongQingJin28 2012-12-03
  • 打赏
  • 举报
回复
文件开始:model.py

import os ;import re

import sys

from PDFNetPython3 import *

from PyQt4.QtGui import *

from PyQt4.QtCore import *

#修改点

mulu = r'D:\Books' #一个目录 他的子目录内有pdf文件

class xml_content:

#修改点 python是一个子目录的名称

def __init__(self ,source = r'Python'):

'''

初始化自己的一些东西

'''

PDFNet.Initialize()

self.source = source # 首先打开的目录

self.pdfdir = {} # 名称 --> 路径

self.pdfcontent ={} # 路径 --> 内容(用于关键字的搜索)

self.pdftree_item ={} # 路径 --> tree_item(用于更新view)

self.find_pdf()

#得到所有的数据

def get_dir(self):

return self.pdfdir

def get_content(self):

return self.pdfcontent

def set_path(self, source): #重新搜索新的路径

''' 重新搜索子文件夹 '''

self.source = source

self.pdfdir = {}

self.find_pdf()

#1.2.0 得到书签

def get_book_mark(self ,FirstBookmark):

content = []

while FirstBookmark.IsValid():

indent = FirstBookmark.GetIndent() - 1

a = ' ' * indent

content.append(a + FirstBookmark.GetTitle())

if FirstBookmark.HasChildren():

content.extend(self.get_book_mark(FirstBookmark.GetFirstChild()))

FirstBookmark = FirstBookmark.GetNext()

return content

#1.2 寻找pdf内的书签

def find_in_pdf(self ,searched):

'''得到所有的pdf书签 并保存到pdfcontent中'''

self.searched = searched

if(not searched):

return list(self.pdfdir.keys())

finded = []

for file in self.pdfdir.keys(): #在所有的文件之中遍历

file_path = self.pdfdir[file]

if(not self.pdfcontent.__contains__(file_path)):

doc = PDFDoc(file_path) #先确定所有的content是存在的

doc.InitSecurityHandler()

root = doc.GetFirstBookmark()

content = self.get_book_mark(root )

joined = '\n'.join(content)

self.pdfcontent[file_path] = joined

doc.Close()

for file in self.pdfdir.keys(): #在所有的文件之中遍历

content = self.pdfcontent[self.pdfdir[file]]

if(re.search(self.searched,content)):

finded.append(file)

return finded

#1. 在指定的目录中找到所有的pdf文件

def find_pdf(self):

global mulu

lists = os.listdir(mulu+'\\'+self.source)

for file in lists:

full_path = mulu+'\\'+self.source+'\\'+file

if(not os.path.isdir(full_path) and full_path.endswith('.pdf')):

self.pdfdir[file.replace('.pdf','')] = full_path

#3.1 添加到widget item是书签的item parent是Wight或是treeItem

def add_to_widget (self, item , treeWight):

item_list = []

while item.IsValid():

cur_item = QTreeWidgetItem(treeWight) #建立widgt的顶层目录

cur_item.setText(0,item.GetTitle()) #设置显示的名字

cur_item.setData(2,Qt.UserRole,item) #底层数据column 2

#书签除了goto还能够是什么呢?

action = item.GetAction()

if action.IsValid():

if action.GetType() == Action.e_GoTo:

dest = action.GetDest()

if dest.IsValid():

page = dest.GetPage()

position = str(page.GetIndex())

cur_item.setData(1,Qt.UserRole,position) #设置跳转的页数 column 0

else:

cur_item.setData(1,Qt.UserRole,None) #设置跳转的页数 为空

item = item.GetNext()

item_list.append(cur_item)

#广度优先的算法 先计算所有的子元素,再计算子元素的子元素

for tree_item in item_list:

if tree_item.data(2,Qt.UserRole).HasChildren():

self.add_to_widget(tree_item.data(2,Qt.UserRole).GetFirstChild(),tree_item)

if(type(treeWight) is QTreeWidget):

treeWight.insertTopLevelItems(0,item_list)

return item_list

else:

treeWight.addChildren(item_list)

#3. 只显示当前这本书的书签

def set_viewer(self,book,item_widgt):

'''

先隐藏掉在treeview中的所有

然后查看是否有已经初始化的treeItem

没有则初始化之

显示即可

'''

n = item_widgt.topLevelItemCount()

for i in range(n):

item_widgt.topLevelItem(i).setHidden(True)

if(book in self.pdftree_item.keys()):

for item in self.pdftree_item[book]:

item.setHidden(False)

else:

doc = PDFDoc(book)

doc.InitSecurityHandler()

root = doc.GetFirstBookmark() #得到第一个书签

bookMarks = self.add_to_widget(root,item_widgt) #添加所有的书签

self.pdftree_item[book] = bookMarks

doc.Close()

if __name__ == '__main__':

test = xml_content()

print(test.get_dir())

文件结束:model.py

文件开始:main.py

import os

import sys

from PyQt4.QtCore import *

from PyQt4.QtGui import *

import dia ; import model ;import sys

import os ; import re

#修改点 用于打开pdf的程序 要能够接受 -n 参数

pdf_exe = r'C:\cygwin\bin\pdf.exe '

class myDia(QDialog,dia.Ui_Dialog):

def __init__(self ):

super(myDia,self).__init__()

self.setupUi(self)

self.search_generator = None

self.item_list=[]

self.init_list() #1. 创建列表

#1. 创建列表

def init_list(self):

self.model = model.xml_content()

mhash = self.model.get_dir()

for aa in mhash.keys():

item = QListWidgetItem(aa)

item.setData(1,mhash[aa])

self.item_list.append(item) #保存所有的item

self.listWidget.addItem(item)

self.add_action() #1.0 给list添加弹出菜单

self.zip_comments = self.model.get_content()

print('initOk')

#1.0 添加弹出菜单

def add_action(self):

self.listWidget.setContextMenuPolicy(Qt.ActionsContextMenu)

self.textBrowser.setContextMenuPolicy(Qt.ActionsContextMenu)

#1.0.0私有方法 创建Action

run_action = self.createAction("Open pdf",slot = self.open_pdf_file)

self.listWidget.addAction(run_action)

dir_action = self.createAction("Open Dir",slot = self.dir_script)

self.listWidget.addAction(dir_action)

bookmark_action = self.createAction("open Book Mark",slot = self.open_bookmark)

self.textBrowser.addAction(bookmark_action)

#1.0.0私有方法 创建Action

def createAction(self, text, slot=None, shortcut=None, icon=None,tip=None, checkable=False, signal="triggered()"):

action = QAction(text, self)

if icon is not None:

action.setIcon(QIcon("/%s.png" % icon))

if shortcut is not None:

action.setShortcut(shortcut)

if tip is not None:

action.setToolTip(tip)

action.setStatusTip(tip)

if slot is not None:

self.connect(action, SIGNAL(signal), slot)

if checkable:

action.setCheckable(True)

return action

#2.0 Action : 用系统文件打开它就可以了

def open_pdf_file(self):

global pdf_exe

cur_itm = self.listWidget.currentItem()

print('the cur item is',cur_itm.data(1))

path = cur_itm.data(1)

os.system(pdf_exe+path)

#2.0 Action : 打开所在目录

def dir_script(self):

cur_itm = self.listWidget.currentItem()

print('the cur item is',cur_itm.data(1))

path = cur_itm.data(1)

filename = re.search(r'(\\[^\\]*?\.pdf)',path).group(1)

path = path.replace(filename,'')

os.system(r'explorer '+path)

#打开书签

def open_bookmark(self):

global pdf_exe

cur_itm = self.listWidget.currentItem()

print('the cur item is',cur_itm.data(1))

path = cur_itm.data(1)

items = self.textBrowser.selectedItems()

if(not items):

return

else :

item = items[0]

position = str(item.data(1,Qt.UserRole))

print('position',position)

if(position):

print('go to bookmark ',position)

print(pdf_exe+'"'+path+'"'+' -n '+position)

os.system(pdf_exe+'"'+path+'"'+' -n '+position)

else:

os.system(pdf_exe+path)

pass

#3.0 event : 根据item的改变而变换信息

@pyqtSignature("QListWidgetItem *,QListWidgetItem *")

def on_listWidget_currentItemChanged(self,item_new,item_old):

if(item_new is None):

return

print('the item change',item_new.data(1))

self.model.set_viewer(item_new.data(1),self.textBrowser)

self.on_lineEdit_textChanged(self.lineEdit.text()) #同时也将搜索清空

#3.0 event : comboBox的值变化了

@pyqtSignature("QString")

def on_comboBox_currentIndexChanged(self ,string):

print('the item change',string)

self.model.set_path(string)

mhash = self.model.get_dir()

self.listWidget.clear()

self.item_list = []

for aa in mhash.keys():

item = QListWidgetItem(aa)

item.setData(1,mhash[aa])

self.item_list.append(item) #保存所有的item

self.listWidget.addItem(item)

#双击 其实就是open_pdf_file

@pyqtSignature("QListWidgetItem *")

def on_listWidget_itemDoubleClicked(self,item_new):

#print('the item double clicked',item_new.data(1))

self.open_pdf_file()

#过滤器

@pyqtSignature("")

def on_lineEdit_returnPressed(self):

text = self.lineEdit.text()

search_keys = self.model.find_in_pdf(text)

finded_item = []

for item in self.item_list:

item.setHidden(True)

full_path = item.text()

if(full_path in search_keys):

finded_item.append(item)

if(finded_item):

for item in finded_item:

item.setHidden(False)

self.listWidget.setItemSelected(finded_item[0],True)

self.on_listWidget_currentItemChanged(finded_item[0],None)

#设置要搜索的东西

@pyqtSignature("QString")

def on_lineEdit_textChanged(self ,text):

#print('text chaned ',text)

self.searched = text

self.search_generator = None

#双击事件

@pyqtSignature("QTreeWidgetItem *,int")

def on_textBrowser_itemDoubleClicked(self ,item,index):

#print('on_textBrowser_itemDoubleClicked',item,index)

self.open_bookmark()

#处理F3

def event(self, event):

if (event.type() == QEvent.KeyPress and

event.key() == Qt.Key_F3):

self.search() #Action 搜索 (F3)

self.textBrowser.setFocus()

return True

return QDialog.event(self, event)

#Action 搜索 (F3) main

def search(self):

self.textBrowser.childCount = self.textBrowser.topLevelItemCount

self.textBrowser.child = self.textBrowser.topLevelItem

self.__searched=[]

if(not self.search_generator):

self.search_item(self.textBrowser)

self.search_generator = self.search_in()

try:

item = self.search_generator.__next__()

#print('yousearched item ',item.text(0))

self.textBrowser.scrollToItem(item)

self.textBrowser.setItemSelected(item,True)

except StopIteration:

self.search_generator = None

#Action 搜索 遍历所有的元素 为yield做准备

def search_item(self, parentitem):

top_count = parentitem.childCount()

for top in range(0,top_count):

item = parentitem.child(top)

if(re.search(self.searched,item.text(0),flags = 2)):

self.__searched.append(item)

if(item.childCount()>0): #添加所有的书签

self.search_item(item)

#Action 搜索 用yield得到已经搜索的

def search_in(self,):

for item in self.__searched:

yield item

def main(arg = None):

app = QApplication(sys.argv)

form = myDia()

form.show()

app.exec_()

if __name__ == "__main__":

main()

文件结束:main.py

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧