51. Python 数据处理(2)
1.Python 修改excel文件
import?xlrd import?xlutils.copy excelr?=?xlrd.open_workbook("hello.xlsx") excelw?=?xlutils.copy.copy(excelr) sheet1?=?excelw.get_sheet(0) sheet1.write(3,?5,?"xlutils.copy?test?test") excelw.save("hello.xlsx")? #?這里如果名稱不變,則覆蓋原文件,如果名稱改變,則生成新名稱的文件。#所以,由上代碼可以分析出,如果文件原本就存在,而你要修改它,不能直接使用xlwt,必須使用 xlutils.copy 方法復制一份出來再修改,最后保存或覆蓋原文件。
#原表格內容
#改后表格內容
2. python 創建新的excel文件,指定標簽頁,并寫入內容到應標簽頁內
import?xlwt excel?=?xlwt.Workbook("hello.xlsx") sheet1?=?excel.add_sheet("sheet5") sheet2?=?excel.add_sheet("sheet2") sheet3?=?excel.add_sheet("sheet3") sheet1.write(0,0,"hello?world") sheet2.write(1,0,"hello") sheet3.write(2,0,"test?test") excel.save("hello1.xlsx")執行結果:
打開hello1.xlsx
3.處理pdf文件
(1) 讀取pdf文件
python3 安裝 pdfminer3k
#?pip?install?pdfminer3kfrom?pdfminer.pdfparser?import?PDFParser,PDFDocument from?pdfminer.pdfparser?import?PDFPage from?pdfminer.pdfinterp?import?PDFResourceManager,PDFTextExtractionNotAllowed from?pdfminer.pdfinterp?import?PDFPageInterpreter from?pdfminer.pdfdevice?import?PDFDevice from?pdfminer.layout?import?LAParams from?pdfminer.converter?import?PDFPageAggregator#獲取文檔對象,你把algorithm.pdf換成你自己的文件名即可。 fp=open("C:\\Users\\Shinelon\\PycharmProjects\\Python3\\datachuli\\aminglinux\\chapter1.pdf","rb") #創建一個與文檔相關聯的解釋器 parser=PDFParser(fp) doc=PDFDocument() parser.set_document(doc) doc.set_parser(parser) #PDF文檔對象,提供密碼初始化,沒有就不用帶password參數。 doc.initialize() #檢查文件是否允許文本提取 if?not?doc.is_extractable:raise?PDFTextExtractionNotAllowed #鏈接解釋器和文檔對象 #parser.set_document(doc) #doc.set_paeser(parser) #初始化文檔 #doc.initialize("") #創建PDF資源管理器對象來存儲共享資源 resource=PDFResourceManager() #參數分析器 laparam=LAParams() #創建一個聚合器 device=PDFPageAggregator(resource,?laparams=laparam) #創建PDF頁面解釋器 interpreter=PDFPageInterpreter(resource,device) #使用文檔對象得到頁面集合 for?page?in?doc.get_pages():#使用頁面解釋器來讀取interpreter.process_page(page)#使用聚合器來獲取內容layout=device.get_result()for?out?in?layout:if?hasattr(out,?"get_text"):print(out.get_text())(2)合并多個pdf文件為一個pdf文件
安裝pypdf2
#?pip?install?pypdf2import?PyPDF2 import?os#?建立一個裝pdf文件的數組 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx """這種方法獲取的文件名列表是按照ascii碼排序的,例如:chapter1.pdf,chapter10.pdf,chapter11.pdf...以此類推""" #?for?fileName?in?os.listdir(r'C:\Users\Shinelon\PycharmProjects\Python3\datachuli\aminglinux'):??#?遍歷該程序所在文件夾內的文件 #?????if?fileName.endswith('.pdf'):??#?找到以.pdf結尾的文件 #?????????pdfFiles.append(fileName)??#?將pdf文件裝進pdfFiles數組內 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"""這種方式可以采用,但是應該還有更好的方法,再想想""" pdfFiles?=?[] for?i?in?range(1,?27):pdfFiles.append("chapter{0}.pdf".format(i))os.chdir(r"C:\Users\Shinelon\PycharmProjects\Python3\datachuli\aminglinux") pdfWriter?=?PyPDF2.PdfFileWriter()??#?生成一個空白的pdf文件for?pdf?in?pdfFiles:pdfReader?=?PyPDF2.PdfFileReader(open(pdf,?'rb'))??#?以只讀方式依次打開pdf文件for?pageNum?in?range(pdfReader.numPages):print(pdfReader.getPage(pageNum))pdfWriter.addPage(pdfReader.getPage(pageNum))??#?將打開的pdf文件內容一頁一頁的復制到新建的空白pdf里pdfOutput?=?open('combine.pdf',?'wb')??#?生成combine.pdf文件 pdfWriter.write(pdfOutput)??#?將復制的內容全部寫入combine.pdf pdfOutput.close()3.Python 處理圖片
圖像處理是一門應用非常廣泛的技術,而擁有非常豐富第三方擴展庫的python當然不會錯過。
PIL(Python Imaging Library)是python種最常用的圖像處理庫,如果你是python2.x,可以通過一下地址進行下載:http://www.pythonware.com/products/pil/index.htm,找到對應的版本進行下載。
【注意】PIL模塊在python3.x中已經替換為pillow模塊,文檔地址:
http://pillow.readthedocs.io/en/latest/
直接使用
pip?install?pillow也可以安裝模塊
導入時使用 from PIL import Image
簡單例子:
from?PIL?import?Image image?=?Image.open("img.jpg") print?(image.format,?image.size,?image.mode) image.show()結果:
JPEG (580, 326) RGB
并把圖片打開,展示出來
由上例子可以知道:
Image的三個屬性:
????format : ?識別圖像的源格式,如果該文件不是從文件中讀取的,則被置為 None 值。
????size : ? ? ? 返回的一個元組,有兩個元素,其值為象素意義上的寬和高。
????mode : ??RGB(true color image),此外還有,L(luminance),CMTK(pre-press image)。
Image的方法介紹:
????show():顯示最近加載的圖像
????open(infilename): ?打開文件
????save(outfilename):保存文件
????crop((left, upper, right, lower)):從圖像中提取出某個矩形大小的圖像。它接收一個四元素的元組作為參數,各元素為(left, upper, right, lower),坐標系統的原點(0, 0)是左上角。【即摳圖】
Image的幾何處理:
????out = im.resize((128, 128)) ? ? ? ? ? ? ? ? ? ? #調整圖片大小
????out = im.rotate(45) ? ? ? ? ? ? ? ? ? ? ? ? ? ? #逆時針旋轉 45 度角。
????out = im.transpose(Image.FLIP_LEFT_RIGHT) ? ? ? ????????#左右對換。
????out = im.transpose(Image.FLIP_TOP_BOTTOM) ? ? ? #上下對換。
????out = im.transpose(Image.ROTATE_90) ? ? ? ? ? ? #旋轉 90 度角。
????out = im.transpose(Image.ROTATE_180) ? ? ? ? ? ?#旋轉 180 度角。
????out = im.transpose(Image.ROTATE_270) ? ? ? ? ? ?#旋轉 270 度角。
例一:摳圖
圖片:
腳本:
from?PIL?import?Image image?=?Image.open("img.jpg") print(image.format,?image.size,?image.mode) box?=?(170,?0,?390,?260) region?=?image.crop(box) region.save("cutting.jpg")摳取過程:
解釋:上述代碼將圖片的((170, 0), (170, 260), (390, 0), (390, 260))所畫出來的區域進行裁剪,并保存在cutting.jpg中
結果L:
史上最強驅逐艦,大家一起來感受一下~_(:3 」∠)_
例子2:圖片拼合
將圖片摳出來,旋轉180度后,在貼回圖片上
from?PIL?import?Image image?=?Image.open("img.jpg") print(image.format,?image.size,?image.mode) box?=?(170,?0,?390,?260) egion?=?image.crop(box) egion.save("cutting.jpg") region?=?egion.transpose(Image.ROTATE_180) image.paste(region,?box) image.show()效果:
例子3:縮放
from?PIL?import?Image infile?=?"img.jpg" outfile?=?"img2.jpg" image?=?Image.open(infile) (x,?y)?=?image.size newx?=?300??????#縮小尺寸 newy?=?int(y*newx/x) out?=?image.resize((newx,?newy),?Image.ANTIALIAS) out.show() out.save(outfile)對比一下:
縮放圖:
例子4:驗證碼(已封裝)
代碼如下:
import?random import?string from?PIL?import?Image,?ImageDraw,?ImageFont,?ImageFilterclass?VerCode(object):def?__init__(self):#?字體的位置,不同版本的系統會有不同self.font_path?=?'consolai.ttf'#?生成幾位數的驗證碼self.number?=?4#?生成驗證碼圖片的高度和寬度self.size?=?(100,?30)#?背景顏色,默認為白色self.bgcolor?=?(255,?255,?255)#?字體顏色,默認為藍色self.fontcolor?=?(0,?0,?255)#?干擾線顏色。默認為紅色self.linecolor?=?(255,?0,?0)#?是否要加入干擾線self.draw_line?=?True#?加入干擾線條數的上下限self.line_number?=?20#?用來隨機生成一個字符串def?gene_text(self):self.source?=?list(string.ascii_letters)for?self.index?in?range(0,?10):self.source.append(str(self.index))return?''.join(random.sample(self.source,?self.number))??#?number是生成驗證碼的位數#?用來繪制干擾線def?gene_line(self,?draw,?width,?height):self.begin?=?(random.randint(0,?width),?random.randint(0,?height))self.end?=?(random.randint(0,?width),?random.randint(0,?height))draw.line([self.begin,?self.end],?fill=self.linecolor)#?生成驗證碼def?gene_code(self):self.width,?self.height?=?self.size??#?寬和高self.image?=?Image.new('RGBA',?(self.width,?self.height),?self.bgcolor)??#?創建圖片self.font?=?ImageFont.truetype(self.font_path,?25)??#?驗證碼的字體self.draw?=?ImageDraw.Draw(self.image)??#?創建畫筆self.text?=?self.gene_text()?????????????????#?生成字符串self.font_width,?self.font_height?=?self.font.getsize(self.text)self.draw.text(((self.width?-?self.font_width)?/?self.number,?(self.height?-?self.font_height)?/?self.number),?self.text,?font=self.font,?fill=self.fontcolor)??#?填充字符串if?self.draw_line:for?i?in?range(self.line_number):self.gene_line(self.draw,?self.width,?self.height)def?effect(self):#self.image?=?self.image.transform((self.width?+?20,?self.height?+?10),?Image.AFFINE,?(1,?-0.3,?0,?-0.1,?1,?0),?Image.BILINEAR)??#?創建扭曲self.image?=?self.image.filter(ImageFilter.EDGE_ENHANCE_MORE)??#?濾鏡,邊界加強self.image.save('idencode.png')??#?保存驗證碼圖片#self.image.show()if?__name__?==?"__main__":vco?=?VerCode()vco.gene_code()vco.effect()效果:
轉載于:https://blog.51cto.com/286577399/2062340
總結
以上是默认站点為你收集整理的51. Python 数据处理(2)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android FrameWork学习(
- 下一篇: 镜像VirtualBox 下安装 Cen