1、CSV数据处理html
CSV文件格式:逗号分隔值(Comma-Separated Value,CSV,有时也称为字符分隔值,由于分隔符也能够不是逗号),其文件以纯文本形式存储表格数据(数字和文本)。纯文本意味着该文件是一个字符序列,不含必须像二进制数字那样被解读的数据。CSV文件由任意数目的记录组成,记录间以某种换行符分隔;每条记录由字段组成,字段间的分隔符是其它字符或字符串,最多见的是逗号或制表符。一般,全部记录都有彻底相同的字段序列。如如下格式:python
27,20,14,15,12,94,13,16,988,1015,0.00,152数组
csv文件能够直接用Excel或者相似软件打开,样子都是咱们常见的表格格式。session
代码例子:app
import csv fileName = 'weather.csv' with open(fileName, "r", encoding="utf-8") as f: text = csv.reader(f) for i in text: print(i) print("####"*10) with open(fileName, "r", encoding="utf-8") as f: for i in f.readlines(): print(i.split(","))
2、Excel数据处理dom
Python提供有第三方库来支持对exec的操做,Python处理Excel文件用的第三方模块库有xlrd、xlwt、xluntils和pyExcelerator,除此以外,Python处理Excel还能够用win32com和openpyxl模块。ide
须要先安装第三方库:pip install xlrd pip install xlwt pip install xluntils pip install pyExcelrator字体
xlrd:读取我Excel文件this
xlwt:写入文件,可是不能在已有的Excel的文件进行修改,若是有这个需求,就须要使用xluntils模块了。google
pyExcelerator模块与xlwt相似,也能够用来生成Excel文件
1.读取单表文件:
def readExcel(): data = xlrd.open_workbook('test.xlsx') table = data.sheets()[0] # 打开第一张表 nrows = table.nrows # 获取表的行数 for i in range(nrows): # 循环逐行打印 print(table.row_values(i))#经过row_values来获取每行的值 readExcel()
# 打开一个workbook workbook = xlrd.open_workbook('testdata.xlsx') # 抓取全部sheet页的名称 worksheets = workbook.sheet_names() print(workbook.sheets()) print('worksheets is {0}'.format(worksheets)) # 定位到sheet1 # worksheet1 = workbook.sheet_by_name(u'Sheet1') worksheet1 = workbook.sheets()[1] """ #经过索引顺序获取 worksheet1 = workbook.sheets()[0] """ """ #遍历全部sheet对象 for worksheet_name in worksheets: worksheet = workbook.sheet_by_name(worksheet_name) """ # 遍历sheet1中全部行row num_rows = worksheet1.nrows for curr_row in range(num_rows): row = worksheet1.row_values(curr_row) print('row%s is %s' % (curr_row, row)) # 遍历sheet1中全部列col num_cols = worksheet1.ncols for curr_col in range(num_cols): col = worksheet1.col_values(curr_col) print('col%s is %s' % (curr_col, col)) # 遍历sheet1中全部单元格cell for rown in range(num_rows): for coln in range(num_cols): cell = worksheet1.cell_value(rown, coln) print(cell)
2.写入Excel文件
import xlwt #建立workbook和sheet对象 workbook = xlwt.Workbook() #注意Workbook的开头W要大写 sheet1 = workbook.add_sheet('sheet1', cell_overwrite_ok=True) sheet2 = workbook.add_sheet('sheet2', cell_overwrite_ok=True) sheet3 = workbook.add_sheet('sheet3', cell_overwrite_ok=True) #向sheet页中写入数据 sheet1.write(0,0,'this should overwrite1') sheet1.write(0,1,'aaaaaaaaaaaa') sheet2.write(0,0,'this should overwrite2') sheet2.write(1,2,'bbbbbbbbbbbbb') #-----------使用样式----------------------------------- #初始化样式 style = xlwt.XFStyle() #为样式建立字体 font = xlwt.Font() font.name = 'Times New Roman' font.bold = True #设置样式的字体 style.font = font #使用样式 sheet3.write(0,1,'some bold Times text',style) #保存该excel文件,有同名文件时直接覆盖 workbook.save('test2.xls') print('建立excel文件完成!')
3.Excel处理超连接
import codecs import xlwt book = xlwt.Workbook() sheet_index = book.add_sheet('index') line=0 for i in range(9): link = 'HYPERLINK("{0}.txt", "{1}_11111")'.format(i, i) sheet_index.write(line, 0, xlwt.Formula(link)) line += 1 book.save('simple2.xls') for i in range(0, 9): file = str(i) + ".txt" with codecs.open(file, 'w') as f: f.write(str(i)*10)
4.修改Excel文件,须要注意的是不支持使用xlsx文件
import xlrd import xlutils.copy #打开一个workbook rb = xlrd.open_workbook('aaa111.xls') wb = xlutils.copy.copy(rb) #获取sheet对象,经过sheet_by_index()获取的sheet对象没有write()方法 ws = wb.get_sheet(0) #写入数据 ws.write(10, 10, 'changed!') #添加sheet页 wb.add_sheet('sheetnnn2',cell_overwrite_ok=True) #利用保存时同名覆盖达到修改excel文件的目的,注意未被修改的内容保持不变 wb.save('aaa111.xls')
3、HTML转PDF文件
转换成PDF文件的三种方法:在工做中,咱们可能会遇到把HTML文件转换成PDF文件,而Python给咱们提供了pdfkit这个模块,咱们直接安装使用就能够了。
pdfkit几个模块的用法:先安装:pip install pdfkit
1.网页转换成PDF:直接把url转换成PDF文件
import pdfkit pdfkit.from_url('http://google.com', 'out1.pdf')
2.html转换成PDF
import pdfkit pdfkit.from_file('test.html', 'out2.pdf')
3.字符串转换成PDF
import pdfkit pdfkit.from_string('Hello lingxiangxiang!', 'out3.pdf')
代码实例:抓取aming的Linux教程。而后制成PDF文件
import codecs import os import sys import pdfkit import requests base_url = 'http://www.apelearn.com/study_v2/' if not os.path.exists("aming"): os.mkdir("aming") os.chdir("aming") s = requests.session() for i in range(1, 27): url = base_url + 'chapter' + str(i) + '.html' print(url) file = str(i) + '.pdf' print(file) config = pdfkit.configuration(wkhtmltopdf=r"D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe") try: pdfkit.from_url(url, file) except: continue
4、Python处理PDF文件
Python读出PDF文件
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/1/10 14:46 # @Author : lingxiangxiang # @File : demon1.py from 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("test.pdf","rb") #建立一个与文档相关联的解释器 parser=PDFParser(fp) #PDF文档对象,提供密码初始化,没有就不用带password参数。 doc=PDFDocument() parser.set_document(doc) doc.set_parser(parser) 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())
合并多个PDF文件为一个PDF文件
import PyPDF2 import os #创建一个装pdf文件的数组 pdfFiles = [] for fileName in os.listdir('aming'): #遍历该程序所在文件夹内的文件 if fileName.endswith('.pdf'): #找到以.pdf结尾的文件 pdfFiles.append(fileName) #将pdf文件装进pdfFiles数组内 # pdfFiles.sort() #文件排序 print(pdfFiles) os.chdir("aming") pdfWriter = PyPDF2.PdfFileWriter() #生成一个空白的pdf文件 for fileName in pdfFiles: pdfReader = PyPDF2.PdfFileReader(open(fileName,'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.pdfpdfOutput.close()
5、Python处理图片
图片处理是一门应用很是广的技术,而拥有很是丰富第三方扩展库的Python固然不会错过这一门盛宴。PIL(Python Imaging Library)是Python中最经常使用的图像处理库。若是是Python2.x,能够经过如下地址进行下载:http://www.pythonware.com/products/pil/index.html,找到相应的版本进行下载。
注意:PIL模块在Python3中已经替换成pillow模块,文档地址:http://pillow.readthedocs.io/en/latest/,直接使用pip3 install pillow便可安装模块。导入时使用from PIL import Image
打开图片
from PIL import Image image = Image.open("1.jpg") print(image.format, image.size, image.mode) image.show()
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)是左上角
例子1:抠图:把头像给截图出来
from PIL import Image image = Image.open("1.jpg") print(image.format, image.size, image.mode) box = (600, 300, 1050, 660) region = image.crop(box) region.save("cutting.jpg")
例子2:图片拼合
from PIL import Image image = Image.open("1.jpg") print(image.format, image.size, image.mode) box = (600, 300, 1050, 660) 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 = "2.jpg" outfile = "new2.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()
例子4:验证码
import random import string import sys import math from PIL import Image, ImageDraw, ImageFont, ImageFilter # 字体的位置,不一样版本的系统会有不一样 font_path = 'msyh.ttf' # 生成几位数的验证码 number = 4 # 生成验证码图片的高度和宽度 size = (100, 30) # 背景颜色,默认为白色 bgcolor = (255, 255, 255) # 字体颜色,默认为蓝色 fontcolor = (0, 0, 255) # 干扰线颜色。默认为红色 linecolor = (255, 0, 0) # 是否要加入干扰线 draw_line = True # 加入干扰线条数的上下限 line_number = 20 # 用来随机生成一个字符串 def gene_text(): source = list(string.ascii_letters) for index in range(0, 10): source.append(str(index)) return ''.join(random.sample(source, number)) # number是生成验证码的位数 # 用来绘制干扰线 def gene_line(draw, width, height): begin = (random.randint(0, width), random.randint(0, height)) end = (random.randint(0, width), random.randint(0, height)) draw.line([begin, end], fill=linecolor) # 生成验证码 def gene_code(): width, height = size # 宽和高 image = Image.new('RGBA', (width, height), bgcolor) # 建立图片 font = ImageFont.truetype(font_path, 25) # 验证码的字体 draw = ImageDraw.Draw(image) # 建立画笔 text = gene_text() # 生成字符串 font_width, font_height = font.getsize(text) draw.text(((width - font_width) / number, (height - font_height) / number), text, font=font, fill=fontcolor) # 填充字符串 if draw_line: for i in range(line_number): gene_line(draw, width, height) # image = image.transform((width + 20, height + 10), Image.AFFINE, (1, -0.3, 0, -0.1, 1, 0), Image.BILINEAR) # 建立扭曲 image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界增强 image.save('idencode.png') # 保存验证码图片 # image.show() if __name__ == "__main__": gene_code()