目錄
1 存儲數據
1.1 媒體文件
存儲媒體文件有兩種主要的方式:只獲取文件 URL 鏈接,或者直接把源文件下載下來。在 Python 3.x 版本中, urllib.request.urlretrieve 可以根據文件的 URL 下載文件:
from urllib.request import urlretrieve
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com")
bsObj = BeautifulSoup(html)
imageLocation = bsObj.find("a", {"id": "logo"}).find("img")["src"]
urlretrieve (imageLocation, "logo.jpg")
1.2 把數據存儲到CSV
CSV(Comma-Separated Values,逗號分隔值)是存儲表格數據的常用文件格式。Excel 和很多應用都支持 CSV 格式,每一行都用一個換行符分隔,列與列之間用逗號分隔。常用就是獲取 HTML 表格並寫入 CSV 文件。
import csv
csvFile = open("../files/test.csv", 'w+')
try:
writer = csv.writer(csvFile)
writer.writerow(('number', 'number plus 2', 'number times 2'))
for i in range(10):
writer.writerow( (i, i+2, i*2))
finally:
csvFile.close()
說明:
如果 ../files/test.csv不存在,Python 會自動創建文件(不會自動創建文件夾)。如果文件已經存 在,Python 會用新的數據覆蓋 test.csv 文件。
運行完成後,你會看到一個 CSV 文件:
number,number plus 2,number times 2
0,2,0
1,3,2
1.3 MySQL數據庫
MySQLdb庫或PyMySQL庫,用下面的命令下載並安裝PyMySQL:
$ curl -L https://github.com/PyMySQL/PyMySQL/tarball/pymysql-0.6.2 | tar xz
$ cd PyMySQL-PyMySQL-f953785/
$ python setup.py install
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='1234', db='testdb', charset='utf8')
#使用cursor方法創建一個遊標
cur = conn.cursor()
#使用execute()方法來實現對數據庫的基本操作
cur.execute("SELECT * FROM pages WHERE id=1")
print(cur.fetchone())
cur.close()
conn.close()
1.4 Email
Python 有兩個包可以發送郵件: smtplib 和 email。 email 模塊裏包含了許多實用的郵件格式設置函數,可以用來創建郵件“包
裹”。smtplib 模塊用來設置服務器連接的相關信息。
import smtplib
from email.mime.text import MIMEText
msg = MIMEText("The body of the email is here")
msg['Subject'] = "An Email Alert"
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
1.5 JSON
import json
information = [
{'小區名稱': '小區A', '均價': 8000, '月交易量': 20},
{'小區名稱': '小區B', '均價': 8500, '月交易量': 35},
{'小區名稱': '小區C', '均價': 7800, '月交易量': 50},
{'小區名稱': '小區D', '均價': 12000, '月交易量': 18}]
with open('房屋信息.json', 'w') as fp:
json.dump(information, fp, indent=4, separators=[',', ':'])
with open('房屋信息.json') as fp:
information = json.load(fp)
for info in information:
print(info)
2 文檔讀取
2.1 純文本
把文件存儲爲在線的純文本格式並不常見,但仍然是存在的,並且大多數瀏覽器都可以很好地顯示純文本文件。
from urllib.request import urlopen
textPage = urlopen("http://www.pythonscraping.com/pages/warandpeace/chapter1.txt")
print(str(textPage.read(), 'utf-8'))
2.2 讀取CSV文件
針對在線CSV文件我們常有以下處理措施:
• 手動把 CSV 文件下載到本機,然後用 Python 定位文件位置;
• 寫 Python 程序下載文件,讀取之後再把源文件刪除;
• 從網上直接把文件讀成一個字符串,然後轉換成一個 StringIO 對象,使它具有文件的屬性。
這裏介紹第三種方法,直接從網上讀取。 csv.DictReader函數可以很好地處理CSV文件,csv.DictReader 會返回把 CSV 文件每一行轉換成 Python 的字典對象返回。
from urllib.request import urlopen
from io import StringIO
import csv
data = urlopen("http://pythonscraping.com/files/MontyPythonAlbums.csv").read().decode('ascii', 'ignore')
dataFile = StringIO(data)
dictReader = csv.DictReader(dataFile)
print(dictReader.fieldnames)
for row in dictReader:
print(row)
結果:
['Name', 'Year']
{'Name': "Monty Python's Flying Circus", 'Year': '1970'}
{'Name': 'Another Monty Python Record', 'Year': '1971'}
{'Name': "Monty Python's Previous Record", 'Year': '1972'}
from csv import reader, writer
from random import randrange
from datetime import date, timedelta
fn = 'data.csv'
with open(fn, 'w') as fp:
wr = writer(fp) # 創建csv文件寫對象
wr.writerow(['日期', '銷量']) # 寫入表頭
# 第一天的日期,2020年1月1日
startDate = date(2020, 1, 1)
for i in range(100): # 生成100個模擬數據
amount = 500 + i*5 + randrange(5,50) # 生成一個模擬數據,寫入csv文件
wr.writerow([str(startDate), amount])
startDate = startDate + timedelta(days=1) # 下一天
# 讀取並顯示上面代碼生成的csv文件內容
with open(fn) as fp:
for line in reader(fp):
if line:
print(*line)
2.3 PDF文件
PDFMiner3K 就是一個非常好用的庫(是 PDFMiner 的 Python 3.x 移植版)。它非常靈活,可以通過命令行使用,也可以整合到代碼中。它還可以處理不同的語言編碼,而且對網絡文件的處理也非常方便。
下面的例子可以把任意 PDF 讀成字符串,然後用 StringIO 轉換成文件對象:
from urllib.request import urlopen
from pdfminer.pdfinterp import PDFResourceManager, process_pdf
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from io import StringIO
from io import open
def readPDF(pdfFile):
rsrcmgr = PDFResourceManager()
retstr = StringIO()
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, laparams=laparams)
process_pdf(rsrcmgr, device, pdfFile)
device.close()
content = retstr.getvalue()
retstr.close()
return content
pdfFile = urlopen("http://pythonscraping.com/pages/warandpeace/chapter1.pdf")
outputString = readPDF(pdfFile)
print(outputString)
pdfFile.close()
readPDF 函數最大的好處是,如果你的 PDF 文件在電腦裏,你就可以直接把 urlopen 返回的對象 pdfFile 替換成普通的 open() 文件對象:pdfFile = open("../pages/warandpeace/chapter1.pdf", 'rb')。主要是針對純文本
3 Word、Excel、PowerPoint文件操作
def checkdocx(dstStr, fn):
# 打開docx文檔
document = Document(fn)
# 遍歷所有段落文本
for p in document.paragraphs:
if dstStr in p.text:
return True
# 遍歷所有表格中的單元格文本
for table in document.tables:
for row in table.rows:
for cell in row.cells:
if dstStr in cell.text:
return True
return False
def checkxlsx(dstStr, fn):
# 打開xlsx文件
wb = load_workbook(fn)
# 遍歷所有工作表的單元格
for ws in wb.worksheets:
for row in ws.rows:
for cell in row:
try:
if dstStr in cell.value:
return True
except:
pass
return False
def checkpptx(dstStr, fn):
presentation = Presentation(fn) # 打開pptx文檔
# 遍歷所有幻燈片
for slide in presentation.slides:
for shape in slide.shapes:
if shape.shape_type == 19: # 表格中的單元格文本
for row in shape.table.rows:
for cell in row.cells:
if dstStr in cell.text_frame.text:
return True
elif shape.shape_type == 14: # 文本框
try:
if dstStr in shape.text:
return True
except:
pass
return False