python總結(201806-201808)

python總結(201806-201808)

主要總結近期工作和自學中的python知識點

  • python的csv文件讀寫
  • python的郵件發送
  • python數據分析畫圖
  • python數據分析的excle表格使用
  • python爬蟲
  • 瞭解python機器學習
  • 使用python3版本

其中大部分是在看書的實際練習,書名:

Python爬蟲開發與項目實戰.pdf
利用Python進行數據分析(目錄,模糊).pdf
Python核心編程 第3版 中文版.pdf

機器學習的知識點來自於github:
https://github.com/Avik-Jain/100-Days-Of-ML-Code

數據分析的知乎帖子:
https://www.zhihu.com/question/29265587


python的csv文件讀寫

因爲python的使用中常涉及到csv的讀寫,使用csv庫,同時指出如何帶有標籤的數據展示:

import csv
from collections import namedtuple

headers=['ID','USERNAME','PASSWORD','AGE','COUNTRY']

rows=[(1001,'qieye','qyie_pass',24,'China'),
      (1002,'mayr','mayr_pass',20,'usa'),
      (1002,'uack','ack_pass',20,'usa')]

with open('qiye.csv','w',newline='') as f:
    f_csv=csv.writer(f)
    f_csv.writerow(headers)
    f_csv.writerows(rows)
    f.close()

with open('qiye.csv') as f:
    f_csv=csv.reader(f)
    headers=next(f_csv)
    print(headers)
    for row in f_csv:
        print(row)

with open('qiye.csv') as f:
    ff = csv.reader(f)
    headings = next(ff)
    Row = namedtuple('Row',headings)
    for r in ff:
        row=Row(*r)
        print(row.USERNAME,row.PASSWORD)
        print(row)

python的郵件發送

郵件發送需要使用到email和smtplib庫,發送郵件之前需要先開啓郵箱的stmp功能:

from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr,formataddr
import smtplib


def _format_addr(s):
    name,addr=parseaddr(s)
    return formataddr((Header(name,'utf-8').encode(),addr))

'''發件人地址密碼'''
from_addr='[email protected]'
password='xxxxx'
'''目標郵件地址'''
to_addr='[email protected]'
'''服務器地址'''
smtp_server='smtp.163.com'
'''設置郵件信息'''
msg=MIMEText('python 爬蟲運行異常,異常信息xxxx','plain','utf-8')
msg['From']=_format_addr('一號爬蟲<%s>' %from_addr)
msg['To']=_format_addr('管理員<%s>' %to_addr)
msg['Subject']=Header('一號爬蟲運行狀態','utf-8').encode()
print(msg)
'''發送郵件'''
server=smtplib.SMTP(smtp_server,25)
server.login(from_addr,password)
server.sendmail(from_addr,[to_addr],msg.as_string())
server.quit()

python數據分析畫圖

其中python3的一些庫名稱都有所改變,需要自己導入;

world_country_codes.py

from pygal_maps_world.i18n import COUNTRIES

def get_country_code(country_name):
    #根據指定國家,返回pygal使用的2個字母國別碼
    for code,name in COUNTRIES.items():
        if name == country_name:
            return  code
    return None

world_population.py

import json
import pygal
from pygal.style import LightColorizedStyle,RotateStyle

from world_country_codes import get_country_code as gcd

"""將數據加到列表"""
filename ='resources/population-estimates_json.json'
with open(filename) as f:
    pop_data = json.load(f)

"""打印每個國家人口"""
cc_populations={}
for pop_dict in pop_data:
    if pop_dict['year']=='2010':
        #"region": "WORLD"
        country_name =pop_dict['region']
        population = int(float(pop_dict['population']))
        code =gcd(country_name)
        if code:
            cc_populations[code] = population
            # print(code+':'+str(population))
        # else:
        #     print('ERROR--'+country_name)

#根據人口,分成3組
cc_pops_1,cc_pops_2,cc_pops_3 ={},{},{}
for cc,pop in cc_populations.items():
    if pop<10000000:
        cc_pops_1[cc]=pop
    elif pop<1000000000:
        cc_pops_2[cc] =pop
    else:
        cc_pops_3[cc]=pop
print(len(cc_pops_1),len(cc_pops_2),len(cc_pops_3))

wm_style=RotateStyle('#336699',base_style=LightColorizedStyle)
wm=pygal.maps.world.World(style=wm_style)
wm.title="World Population in 2010,by Country"
wm.add('0-10m', cc_pops_1)
wm.add('10m-1bn', cc_pops_2)
wm.add('>1bn', cc_pops_3)

wm.render_to_file("world_population.svg")

結果:
這裏寫圖片描述
生產的svg文件:world_population.svg,用瀏覽器打開:
這裏寫圖片描述
根據多個骰子的結果統計概率圖:
這裏寫圖片描述

還有數據漫步:
這裏寫圖片描述

python數據分析的excle表格使用

需要根據數據進行分析,編寫數據分析報告,彙報;
主要是使用數據導出數據csv,然後保存到excel中做數據分析,對數據進行清理統計,主要涉及各種excel的各種函數(if,countifs,left,分列,定位,篩選,排序,匹配等),及數據透視表和數據透視圖
數據統計柱狀圖

數據分析餅圖排序
這裏寫圖片描述

python爬蟲

爬蟲只是在看書,瞭解思路,前期各種小的知識點已將有大致瞭解,一個圖片下載的小爬蟲:

import urllib
from lxml import etree
import requests
import urllib.request

def schedule(blocknum,blocksize,totalsize):
    per = 100.0 *blocknum*blocksize/totalsize
    if per >100:
        per =100
    print('當前下載精度:%.2f%%' %per)

user_agent='Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
headers={'User-Agent':user_agent}
# r=requests.get('http://www.ivsky.com/tupian/ziranfengguang/',headers=headers)
r=requests.get('http://www.ivsky.com/tupian/qinwenjiewen_t19482/',headers=headers)
# http://www.ivsky.com/bizhi/dongman_1920x1080/
html=etree.HTML(r.text)
print(html)
img_urls=html.xpath('.//img/@src')
print(img_urls)
i=0
for img_url in img_urls:
    namejpg=img_url.split('/')
    id = len(namejpg)-1
    namejpg=namejpg[id].split('.')[0]
    print(namejpg)
    urllib.request.urlretrieve(img_url,'D:\python-image\img'+namejpg+'.jpg',schedule)
    # i+=1

這裏寫圖片描述

瞭解python機器學習

瞭解機器學習,目前拙見:收集數據,清洗數據,建立模型,根據數據分析各種數學模型的歸納—類似於將數據找到符合的數學模型,然後預測以後的數據分佈;
在github上有童鞋將英文版翻譯成中文:
https://github.com/MachineLearning100/100-Days-Of-ML-Code
這裏寫圖片描述

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章