fateame 发表于 2018-8-7 10:13:04

50. Python 数据处理(1)

  今天开始往后都,用python3来写脚本
  1.csv数据处理
  csv文件格式:
  逗号分隔符(csv),有时也称为字符分隔值,因为分隔字符也可以不是逗号,其文件以纯文本的形式存储表格数据(数字和文本)。
  纯文本意味着该文件是一个字符序列,不含必须像二进制数字那样被解读的数据。
  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 codecs  
lineText = list()
  
with codecs.open("sl_original_live.csv",encoding="utf-8") as f:
  
    for line in f.readlines():
  
      print (line.split(","))#以列表形式,打印每一行的数据。
  
      lineText.append(line.split(","))
  
    print (lineText)#把上面所有行作为元素数据,存入一个列表中。
  csv模块用法,使用模块来处理数据:
import codecs  
import csv
  
fileName = "sl_original_live.csv"
  
with codecs.open(fileName) as fcsv:
  
    linecsv = csv.reader(fcsv)
  
    rows =
  
    print (rows)
  以上了解即可。
  2.excel数据处理
  python 提供有第三方库来支持excel的操作,python处理excel文件用的第三方模块库,有xlrd、xlwt、xluntils和pyExcelerator,
  除此之外,python处理excel还可以用win32com和openpyxl模块.
  我们主要用xlrd、xlwt、xluntils这三个模块,pyExcelerator模块偶尔也会用:
pip install xlrd  
pip install xlwt
  
pip install xlutils
  
pip install pyExcelerator
  xlrd只能进行读取excel文件,没法进行写入文件;
  xlwt可以写入文件,但是不能在已有的excel的文件上进行修改;
  xluntils可以在已有的excel文件上进行修改;
  pyExcelerator与xlwt类似,也可以用来生成excel文件
  读取表单数据:
  举例:按行取数据
import xlrd  
def readExcel():
  
    data = xlrd.open_workbook('test.xlsx')
  
    table = data.sheets() # 打开第一张表
  
    nrows = table.nrows # 获取表的行数
  
    for i in range(nrows): # 循环逐行打印
  
      print(table.row_values(i))#通过row_values来获取每行的值
  

  
if __name__ == '__main__':
  
    readExcel()
  举例:按竖列取数据
import xlrd  
data = xlrd.open_workbook("whsc.xlsx")
  
table2 = data.sheet_by_name("域名")#sheet标签页的名称
  
for col in range(table2.ncols):
  
    print (table2.col_values(col))
  举例:创建新的并写入excel文件(xlwt无法修改原有文件)
import xlwt  
excel = xlwt.Workbook()
  
#创建3个表
  
sheet1 = excel.add_sheet("sheet1")
  
sheet2 = excel.add_sheet("sheet2")
  
sheet3 = excel.add_sheet("sheet3")
  
#只在第一个表sheet1里写数据,如下:
  
sheet1.write(0,0,"hello world1", cell_overwrite_ok=True)
  
sheet1.write(1,0,"hello world2", cell_overwrite_ok=True)
  
sheet1.write(2,0,"hello world3", cell_overwrite_ok=True)
  
#第一个是行,第二个是列,第三个是内容,第二个参数用来确认同一个cell单元是否可以重设值。
  
excel.save("hello.xlsx")
  
print("创建hello.xlsx完成")
  效果如下:

  举例:字体效果
  使用样式,字体类型、加粗等效果:
import xlwt  
excel = xlwt.Workbook()
  
#创建3个表
  
sheet1 = excel.add_sheet("sheet1")
  
sheet2 = excel.add_sheet("sheet2")
  
sheet3 = excel.add_sheet("sheet3")
  
#初始化样式
  
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文件,有同名文件时直接覆盖
  
excel.save('hello.xlsx')
  
print('创建hello.xlsx文件完成!')
  效果如下:

  举例:处理超链接
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)
  
    #{0}.txt是要链接的文件,{1}_11111是链接文件的内容
  
    sheet_index.write(i, 0, xlwt.Formula(link))
  
    #第一个行号,第二个列号,第三个是写入内容link,内容里面超链接
  
book.save('simple2.xlsx')
  
for i in range(0, 9):
  
    file = str(i) + ".txt"
  
    with codecs.open(file, 'w') as f:
  
      f.write(str(i)*10)
  效果如下:

  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')
  三种方法简单例子:
import pdfkit  
pdfkit.from_file("hello.html", 1.pdf)
  
pdfkit.from_url("www.baidu.com", 2.pdf)
  
pdfkit.from_string("hello world", 3.pdf)
  即可生成pdf文件~
  举例:
  抓取aming的linux教程,然后制作成pdf文件
  先抓取每个的网页,然后生成pdf文件
  (1)查看网页源代码

  (2)查看源代码内容

  和url对应规律
  http://www.apelearn.com/study_v2/chapter2.html
  http://www.apelearn.com/study_v2/chapter5.html
  http://www.apelearn.com/study_v2/chapter7.html
  ... ...
  通过 https://regex101.com/ 正则网站,把需要的字段给过滤出来
  
  代码如下(未封装,回头有空封装一下):
import os  
import re
  
import pdfkit
  
import requests
  

  
if not os.path.exists("aminglinux"):
  
    os.mkdir("aminglinux")
  

  
os.chdir("aminglinux")
  

  
url = "http://www.apelearn.com/study_v2/"
  
s = requests.session()
  
text = s.get(url).text
  
reg = re.compile(r'<li class=\&quot;toctree-l1\&quot;><a class=\&quot;reference internal\&quot; href=\&quot;(.*)\&quot;>.*<\/a><\/li>')
  
result = reg.findall(text)
  
res = list(set(result))
  

  
for i in res:
  
    purl = &quot;{0}{1}&quot;.format(url, i)
  
    print (purl)
  
    pdfFileName = i.replace(&quot;html&quot;, &quot;pdf&quot;)
  
    print (pdfFileName)
  
    config = pdfkit.configuration(wkhtmltopdf=r&quot;C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe&quot;)
  
    try:
  
      pdfkit.from_url(purl, pdfFileName, configuration=config)
  
    except:
  
      continue
  执行结果:
页: [1]
查看完整版本: 50. Python 数据处理(1)