python数据处理(二)

摘要:
1、 Csv文件格式2。Excel数据处理2.1。读取单表文件:2.2。读取单表文件复杂示例:2.3。编写excel文件2.5。Python修改excel文件:3。Python处理pdf文件3.1。Python读取pdf文件3.2。抓取每个网页,然后生成pdf文件3.3。Html转换为pdf文件4。Python处理图像4.1。图像的三个属性:4.2、抠图4.3、图像拼接4.4、缩放4.5验证码1。有关csv文件的格式,请参见的定义。csv文件:逗号分隔的值,其文件以纯文本形式存储表数据。

一、csv 文件格式二、excel数据处理2.1读取单表文件:2.2 读取单表文件复杂例子:2.3、写入excel文件2.5、Python进行修改excel文件:三、Python处理pdf文件3.1、Python读出pdf文件3.2、抓取每个的网页,然后生成pdf文件3.3、Html转pdf文件四、Python处理图片4.1 Image的三个属性:4.2、抠图4.3、图片拼合4.4、缩放:4.5、验证码

一、csv 文件格式

看下.csv文件的定义:

逗号分隔值(Comma-Separated
Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)。纯文本意味着该文件是一个字符序列,不含必须像二进制数字那样被解读的数据。CSV文件由任意数目的记录组成,记录间以某种换行符分隔;每条记录由字段组成,字段间的分隔符是其它字符或字符串,最常见的是逗号或制表符。通常,所有记录都有完全相同的字段序列。
如一下格式:

27,20,14,15,14,12,94,64,37,1015,1013,1009,7,5,2,21,8,35,0.00,,,152 .csv

文件可以直接用excel或者类似软件打开,样子都是我们常见的表格形式。

示例一:

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(","))
二、excel数据处理

python提供有第三方库来支持对excel的操作,python处理excel文件用的第三方模块库有xlrd、xlwt、xluntils和pyExcelerator,除此之外,python处理excel还可以用win32com和openpyxl模块。下面我们先安装第三方库:

Pip install xlrd
Pip install xlwt
Pip install xluntils
Pip install pyExcelerator

Xlrd只能进行读取excel文件,没法进行写入文件,xlwt可以写入文件,但是不能在已有的excel的文件上进行修改,如果有这个需求,就需要使用xluntils模块了,pyExcelerator模块与xlwt类似,也可以用来生成excel文件。

2.1读取单表文件:

import xlrd
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()

2.2 读取单表文件复杂例子:

# 打开一个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.3、写入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文件完成!')
2.4、Excele来处理超链接
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)

2.5、Python进行修改excel文件:

但是不支持使用xlsx文件,直接使用xlsx就没有问题,如果使用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')
三、Python处理pdf文件

3.1、Python读出pdf文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/06/09 14:46
# @Author : jiangshan
# @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())

3.2、抓取每个的网页,然后生成pdf文件

import codecs
import os
import sys
import pdfkit
import requests
base_url = 'http://www.okay686.cn/'
if not os.path.exists("okay686"):
os.mkdir("okay686")
os.chdir("okay686")
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 Fileswkhtmltopdfinwkhtmltopdf.exe")
try:
pdfkit.from_url(url, file)
except:
continue

3.3、Html转pdf文件

合并多个pdf文件为一个pdf文件

import PyPDF2
import os #建立一个装pdf文件的数组
pdfFiles = []
for fileName in os.listdir('okay686'): #遍历该程序所在文件夹内的文件
if fileName.endswith('.pdf'): #找到以.pdf结尾的文件
pdfFiles.append(fileName) #将pdf文件装进pdfFiles数组内
# pdfFiles.sort() #文件排序
print(pdfFiles)
os.chdir("okay686")
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.pdf
pdfOutput.close()
四、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/

引用块内容

直接使用

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()
结果:
JPEG (1080, 1920) RGB 并把图片打开,展示出来

4.1 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)是左上角。

4.2、抠图

需求,把头像给截图出来:

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")
上述代码讲图片的((600, 300), (600, 660), (1050, 300), (1050, 660))所画出来的区域进行裁剪,并保存在cutting.jpg中

4.3、图片拼合

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()
把头像照片截取出来,然后调换头像照片180度,然后在拼接在一起,

4.4、缩放:

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.5、验证码

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()

免责声明:文章转载自《python数据处理(二)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇dup和dup2用法小结Easyui的DateBox日期格式化下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

eclipse安装插件的方法,以python为例子

一 转载自:http://www.cnblogs.com/linzhenjie/articles/2639113.html 1、基本需求     1、Eclipse 集成开发环境下载 http://115.com/file/c2vz7io5    JDK6下载 http://115.com/file/c2vz7idq     2、Pydev插件下载  ht...

机器学习算法与Python实践之(七)逻辑回归(Logistic Regression)

http://blog.csdn.net/zouxy09/article/details/20319673 机器学习算法与Python实践之(七)逻辑回归(Logistic Regression) zouxy09@qq.com http://blog.csdn.net/zouxy09 机器学习算法与Python实践这个系列主要是参考《机器学习实战》这本书...

Python数据可视化:网易云音乐歌单

通过Python对网易云音乐华语歌单数据的获取,对华语歌单数据进行可视化分析。 可视化库不采用pyecharts,来点新东西。 使用matplotlib可视化库,利用这个底层库来进行可视化展示。 推荐下我自己创建的Python学习交流群960410445,这是Python学习交流的地方,不管你是小白还是大牛,小编都欢迎,不定期分享干货,包括我整理的一份适合...

函数:Python的乐高积木

函数可以将重复的代码打包起来,再有需要的时候可以不用写代码,直接调用。 一、定义函数 在Python中,定义一个函数要使用def语句,依次写出函数名、括号、括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回。 >>> def MineFunc(): print('调用函数,执行print语句') &g...

Python实现一些常用排序算法

一些常用的排序 #系统内置排序算法#list.sort()#heapq模块 def sys_heap_sort(list): import heapq heap = [] for i in range(len(list)): heapq.heappush(heap,list[i]) for i in rang...

Python获取命令行参数

sys.argv[] 包含命令行参数的字符串列表,通过下标获取参数。 例如: ? #!/usr/bin/python # Filename: using_sys.py    importsys    print'The command line arguments are:' fori insys.argv:     printi    p...