这篇教程如何用python插入独创性声明写得很实用,希望能帮到您。 想必写毕设的时候,大家都会遇到一个问题,那就是得在明评版的论文里面插入一个独创性声明。就因为这个事情,我折腾了好久,各种在线网站都试过了,然而基本都需要充值或者会员啥的。(小声嚷嚷:“万恶的资本”) 害~一不做二不休,我干脆自己写个小工具好了。
一、代码分析
利用PyPDF2库便可轻松地对PDF文件进行处理,具体用法大家可以参考这里。首先是安装这个库: 定义输入和输出对象: # 定义输出对象outputName = 'output.pdf'output = PdfFileWriter()# 定义读取对象thesisPDF = PdfFileReader(open(thesisName,'rb'))insertPDF = PdfFileReader(open(insertName,'rb'))N_page = thesisPDF.getNumPages()pos = int(input('论文一共有"%d"页,请输入需要插入的位置:'%N_page)) 分别读取论文的PDF和独创性声明的PDF,随后将声明插入到论文中的指定页面: # 将声明插入到指定页面for i in range(pos): output.addPage(thesisPDF.getPage(i))output.addPage(insertPDF.getPage(0)) # 插入for i in range(pos,N_page): output.addPage(thesisPDF.getPage(i)) 将结果保存到本地: # 保存插入后的结果output.write(open(outputName,'wb')) 到这里,我们就已经成功的把声明插入到指定的页面中了。你没有看错,就是这么简单~
二、完整代码
将以上几部分整合起来,完整的代码如下: # -*- coding: utf-8 -*-"""Created on Thu Nov 5 20:13:18 2020@author: kimol_love"""import osfrom PyPDF2 import PdfFileWriter, PdfFileReader# 用户输入论文名while True: thesisName = input('请输入论文的文件名:') if not os.path.exists(thesisName): print('文件不存在,请重新输入!') continue if thesisName[-4:].lower() != '.pdf': print('后缀错误,请重新输入!') continue break# 用户输入需要插入的页面while True: insertName = input('请输入声明的文件名:') if not os.path.exists(insertName): print('文件不存在,请重新输入!') continue if thesisName[-4:].lower() != '.pdf': print('后缀错误,请重新输入!') continue break# 定义输出对象outputName = 'output.pdf'output = PdfFileWriter()# 定义读取对象thesisPDF = PdfFileReader(open(thesisName,'rb'))insertPDF = PdfFileReader(open(insertName,'rb'))N_page = thesisPDF.getNumPages()pos = int(input('论文一共有"%d"页,请输入需要插入的位置:'%N_page))# 将声明插入到指定页面for i in range(pos): output.addPage(thesisPDF.getPage(i))output.addPage(insertPDF.getPage(0)) # 插入for i in range(pos,N_page): output.addPage(thesisPDF.getPage(i)) # 保存插入后的结果output.write(open(outputName,'wb'))print('"%s"已经成功插入到"%s"的第%d页'%(insertName,thesisName,pos)) 运行效果如下: 
打开生成的output.pdf,可以发现已经成功插入。
写在最后
最后,感谢各位大大的耐心阅读,咋们下次再会~ 以上就是如何用python插入独创性声明的详细内容,更多关于用python插入独创性声明的资料请关注51zixue.net其它相关文章! python OpenCV学习笔记 python 爬取壁纸网站的示例 |