Python處理CSV,Excel,PDF和圖片

來源:互聯網
上載者:User

標籤:main   藍色   with   manage   min   tran   記錄   files   mina   

使用Python處理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(","))



使用Python處理Excel格式資料

python處理excel檔案用的第三方模組庫有xlrd、xlwt、xluntils和pyExcelerator,除此之外,python處理excel還可以用win32com和openpyxl模組。

使用pip安裝第三方庫

Pip install xlrd

Pip install xlwt

Pip install xluntils

Pip install pyExcelerator

Xlrd只能進行讀取excel檔案,沒法進行寫入檔案,xlwt可以寫入檔案,但是不能在已有的excel的檔案上進行修改,如果有這個需求,就需要使用xluntils模組了,pyExcelerator模組與xlwt類似,也可以用來產生excel檔案。


使用xlrd讀取單表檔案:

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


讀取單表複雜例子:

# 開啟一個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)


使用xlwt寫入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檔案完成!')


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)


使用Python修改Excel表格內容:

不支援使用xlsx檔案,直接使用xls就沒有問題,如果使用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檔案

讀取PDF檔案

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


html轉換為PDF檔案

安裝pdfkit模組

pip install pdfkit

#網頁轉換成pdf

直接把url轉換成pdf檔案

import pdfkit

pdfkit.from_url('http://google.com', 'out1.pdf')

#Html轉換成pdf

Import pdfkit

pdfkit.from_file('test.html', 'out2.pdf')

#字元創轉換成pdf

Import pdfkit

pdfkit.from_string('Hello lingxiangxiang!', 'out3.pdf')


合并多個PDF檔案

import PyPDF2

import os

#建立一個裝pdf檔案的數組

pdfFiles = []

for fileName in os.listdir('XX'):    #遍曆該程式所在檔案夾內的檔案

    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.pdf

pdfOutput.close()




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

並把圖片開啟,展示出來


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 度角。


使用Python摳圖

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中


使用Python拼圖

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度,然後在拼接在一起


使用Python縮放圖片

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


Python處理驗證碼

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處理CSV,Excel,PDF和圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.