目录
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