Google Code Prettify - 輕量級的語法上色工具

顯示具有 Python 標籤的文章。 顯示所有文章
顯示具有 Python 標籤的文章。 顯示所有文章

星期四, 3月 28, 2019

Python Requests

'''
http://httpbin.org/
http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
http://docs.python-requests.org/en/master/

上傳檔案 & Cookie & 不合格憑證
https://zwindr.blogspot.com/2016/08/python-requests.html
'''

import requests

print('======增加 URL 查詢參數')
# 查詢參數
my_params = {'q': 'bugsfamily'}
# 將查詢參數加入 GET 請求中
r = requests.get('https://www.google.com/search', params = my_params, timeout = 3)
re = r.status_code
print('status_code:',re)
print('headers:',r.headers['content-type'])
print('encoding:',r.encoding)
print('TEXT Count bugsfamily Nun:',r.text.count('bugsfamily'))

if r.status_code == requests.codes.ok:
    print("OK")
else:
    print(type(requests.codes.ok))


r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
re = r.status_code
print('status_code:',re)
print('headers:',r.headers['content-type'])
print('encoding:',r.encoding)
print('TEXT:',r.text)
re = r.json()
print('JSON:',re['message'])
if r.status_code == 200:
    print("OK")
else:
    print('Notes:',r.status_code)
       

星期三, 3月 27, 2019

Python 資料分析: Pandas 欄 列 增刪查改

"""
Created on Mon Mar 18 13:22:42 2019

@author: 1277
"""
# -*- coding: utf-8 -*-
import pandas as pd

f='d:\\pyTest\\test.csv'
f = pd.read_csv(f)
print('======前三筆')
print(f.head(3))
print('======後三筆')
print(f.tail(3))
print('======shape')
print(f.shape)
print('======info')
print(f.info())

print('======查詢 DataFrame 0至3筆 ======')
print(f[['Subject','Status']][0:3])

print('======新增 DataFrame columns 方法一')
f.insert(3,column="sport",value="Basketball")
print(f[['Subject','sport','Result']][0:])

print('======新增 DataFrame columns 方法二')
#Dictinary轉DataFrame使用
data = {'name': ['Bob', 'Nancy','Amy','Elsa','Jack'],
        'year': [1996, 1997, 1997, 1996, 1997],
        'month': [8, 8, 7, 1, 12],
        'day':[11,23,8,3,11]}
myframe3 = pd.DataFrame(data,columns=['name','year', 'month', 'day','luckynumber'])

#先List轉成Series
luckynumber = ['3','2','1','7','8']
luckynumber = pd.Series(luckynumber)

#賦予值
myframe3['luckynumber'] = luckynumber
print(myframe3)


print('======新增 DataFrame 一列')
#Dictinary轉成Series
dic_data = {'name':'AAA','year':1955,'month':2,'day':2,'luckynumber':7 }
my_obj = pd.Series(dic_data)

#加入一列
newdata = myframe3.append(my_obj,ignore_index=True)
print(newdata)

# https://www.jianshu.com/p/7df2593a01ce
#也可用concat方式
insert=[['BBB',1999,12,12,55],['CCC',1911,11,11,66]]
insertRow = pd.DataFrame(insert,columns=['name','year', 'month', 'day','luckynumber'])
above = newdata.loc[:2]
below = newdata.loc[3:]

newdata2=pd.concat([above,insertRow,below],ignore_index=True)
print(newdata2)

print('======資料刪除 有N/A 或空白 的列')
f_delna = f.dropna()
print(f_delna[['Subject','sport','Result']][0:])


print('======空白資料填充')
f_na=f.fillna('xxxxx')
print(f_na)

print('======改值方式')

#.loc是對原有DataFrame的一種復制性引用,而[]的引用則是指針性的引用。
#所以用[]賦予值時出現SettingWithCopyWarning是正常的

A = pd.DataFrame([[1,2,3],[2,3,4],[3,4,5]], columns = ['a','b','c'])
B = A[['a', 'b']]
print(B)
B['a'] = B['a'] + 1 # same result by using B.loc[:,'a'] = B.loc[:,'a']+ 1
print(B)

#用.loc這樣就不會出現報警了。
C = A.loc[:,['a','b']]
C['a'] = C['a']+1


星期二, 3月 26, 2019

NumPy及Pandas套件

'''
http://psop-blog.logdown.com/posts/2911380-python-pandas
'''
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(4,2),index=['a', 'a', 'b', 'b'])
print(df)

星期五, 3月 15, 2019

Python 資料分析: Numpy

# -*- coding: utf-8 -*-
"""
numpy 的元數只有數字與float與文字型別
numpy 的元數中有文字則所有型別皆會轉為文字。    #True = 1, False = 0 視為數字型別。
int < folat < string
"""
print(__doc__)

import numpy as np

a=np.array([True,1,'a',3.3,True]) #一維用 List 即可不須用numpy
b=np.array([[1,2,3,4,'a'],['x',2,2,2,'b']])
c=np.array([[1,2,3,4,'a'],[2,2,2,'b']])
print (a,'-',np.shape(a))
print (b,'-',np.shape(b))
print (c,'-',np.shape(c))

for i in a:
    print(type(i),a)          #True = 1, False = 0 視為數字

a = np.arange(15).reshape(3,5)
print(a)
print(a+a)
print(a.shape) #(3,5) 3列5欄
print(a.ndim) #2維
print(a.dtype.name) #int32
print(a.itemsize) #4 由0-4
print(a.size) #15 個數量
print(type(a)) # type

print('oooooooooooooooooooooooooooooo')

from nltk.classify.megam import numpy
#from pandas.core.config_init import doc

print('====== List to Array')
#定义一个list
list=[1,2,3,4,5,6]
print (list,'\t', type(list))

#将list转化为为numpy.ndarray
array=numpy.array(list)
print (array,'\t', type(array))

print('====== Array to List')
#定义一个numpy.ndarray
array=numpy.array([1,2,3,4,5,6])
print (array,'\t', type(array))

#将numpy.ndarray转化为list
list=array.tolist()
print (list,'\t', type(list))

Python 資料分析: Pandas 資料型態 Series & DataFrame

# -*- coding: utf-8 -*-
"""
在學習pandas之前我們要先知道pandas的兩種特有的資料結構DataFrame與Series。
Series格式就是一個一維陣列的資料:
DataFrame就像是我們在使用的excel表格一樣,是一個二維的數據有index和column,可以透過index和column來找到我們要的某一筆資料。
"""
print(__doc__)

import pandas as pd
pd.__version__
# a = List
a=[1,2,3]
print(type(a))
print(a)

print('======Series資料結構')
my_obj = pd.Series([4, 7, -5, 3])
print(type(my_obj))
print(my_obj)
print(my_obj.values)
print(my_obj.index)

seriesObj = pd.Series(range(10),index=['a', 'a', 'b', 'b', 'b','c','c','c','c','c'])
seriesObj['c']

print(seriesObj)
print('======改變Index')
my_obj2 = pd.Series([8,9,10,11], index=['a','b','c','d'])
print(type(my_obj2))
print(my_obj2)
print(my_obj2.values)
print(my_obj2.index)
print('a' in my_obj2)
print(my_obj2['a'])

print('======DataFrame資料結構')
data = {'name': ['Bob', 'Nancy','Amy','Elsa','Jack'],
        'year': [1996, 1997, 1997, 1996, 1997],
        'month': [8, 8, 7, 1, 12],
        'day':[11,23,8,3,11]}
myframe = pd.DataFrame(data)
print(type(myframe))
print(myframe)


星期四, 3月 14, 2019

Python 爬蟲 Beautiful Soup + import re #正規表示式

"""
Crawler
@author: Dazhuang
"""
import requests
from bs4 import BeautifulSoup
import re #正規表示式

s = 0
r = requests.get('https://book.douban.com/')
soup = BeautifulSoup(r.text, 'lxml')
pattern = soup.find_all('a')  # 之前此处标签为'p', 'comment-content'
for item in pattern:
    print(item.string)
pattern_s = re.compile('p = re.findall(pattern_s, r.text)
for star in p:
    s += int(star)
print(s)

Python3 資料結構與使用時機:

# -*- coding: utf-8 -*-
"""
Tuple:資料設定後不能更改。一般用在設定(類似PHP的常數)

List:簡單的資料造訪與計算。一般用在一維資料。可用各式的資料型態。

資料分析使用numpy的array
http://www2.nkfust.edu.tw/~shanhuen/PythonTutorialHtml/NumPy/NumPy1.html

Dictionary:單一關鍵值使用(字典:如 n = { 學生姓名 : [各科成績] ), ....}

Set:不常用。一個無序不重複元素集,可以計算交集、差集、並集等。
Frozenset:不常用。
http://www2.nkfust.edu.tw/~shanhuen/PythonTutorialHtml/_14_set.html

"""
print(__doc__)

print('====== List')
list=[1,2,3.33,True,'a',6]
print (list,'\t', type(list))
for i in list:
    print(type(i),i)


Python 爬蟲 selenium 可以輸入字串、按下enter

selenium

不過如果有很多互動呢?有很多js的code,不是靜態網頁呢?這個就一定要用這個selenium了! 他就是用機器模仿人類點開網站、可以輸入字串、按下enter,再回傳你要的文檔。功能強大! 因為selenium可以和很多語言都可以使用。python 的話,這裡有一個教學。
from selenium import webdriverbrowser = webdriver.Firefox()browser.get('http://python.org')input = browser.find_element_by_tag_name('input')input.send_keys('selenium', Keys.RETURN)
這樣就會讓firefox打開python的官網,輸入”selenium”字串,並且搜尋。 它也有很多內建的find_element(s)by….很多方式來去定位。
另外也有send_keys, 也可以要瀏覽器wait等等很實用的功能喔!

Python 爬蟲 Xpath

講者很快速地提過xpath的好用之處,來上這課之前,我也不太想理會xpath。不過發現真的不錯用啊。 可以在w3cschool上有簡單的introduction 可以參考。 也可以看lxml的官方文件看看xpath怎麼使用

星期三, 3月 13, 2019

Python 爬蟲 Beautiful Soup

# 引入 Beautiful Soup 模組
from bs4 import BeautifulSoup

# 以 Beautiful Soup 解析 HTML 程式碼
soup = BeautifulSoup(html_doc, 'html.parser')

# 原始 HTML 程式碼:在這邊我們先定義ㄧ個html類型的檔案
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
# 輸出排版後的 HTML 程式碼
print(soup.prettify())

# 測試
soup.title.string
soup.find("a")
soup.find("a").text
soup.find("a").string
soup.find("a").get('id')
soup.find("a").get('href')
soup.find("a").get('class')
soup.find_all("a")
for link in soup.find_all('a'):
    print(link.get('href'))   # 輸出超連結

for tag in soup.find_all('a'):
    print(tag.string)    # 輸出超連結的文字


# CSS Select
soup.find_all(id="link3")
soup.select("title")
soup.select("body a ")
soup.select("body a ")[2]
soup.select("body a ")[2].text
soup.select("body a ")[2].string
soup.select("body a ")[2].get('id')
soup.select("body a ")[2].get('href')
soup.select("body a ")[2].get('class')

# 搜尋所有超連結與粗體字
soup.find_all(["a", "b"])

# 限制搜尋結果數量
soup.find_all(["a", "b"], limit=2) 

# 預設會以遞迴搜尋 
soup.html.find_all("title") 

# 不使用遞迴搜尋,僅尋找次一層的子節點 
soup.html.find_all("title", recursive=False)

Python 質數

# -*- coding: utf-8 -*-
"""
Created on Fri Mar 15 08:37:20 2019
@author: 1277
"""
print(__doc__)
def is_prime(n):
    for i in range(2, n):
        if n % i == 0:  # 整除,i 是 n 的因數,所以 n 不是質數。
            return False
    return True     # 都沒有人能整除,所以 n 是質數。


factor= []
for n in range(2,38):
    if is_prime(n):
        print(n,is_prime(n))
        factor.append(n)
        print(factor)
    else:
        print(n,is_prime(n))
     

Python 常用模組 model

#數學
import math
dir(math)
math.pi
help(math.pi)

#檔案
import os
os.getcwd()
path='c:\test\'
os.chdir( path )
os.rename()
os.remove()

#亂數
import random
#random.shuffle('a'.'b'.'c') #打亂排序
print(random.choice(['a','b','c']))
print(random.randint(0,100))
 #打亂排序必須用LIST
list = [20, 16, 10, 5];
random.shuffle(list)
print ("随机排序列表 : ",  list )
random.shuffle(list)
print ("随机排序列表 : ",  list )

#時間
import datetime
dir(datetime)
from datetime import date
date.today
from datetime import time
time(23,23,59)
from datetime import datetime
dt = datetime.now()
dt
print (dt.strftime('%a, $b %d %Y %H :%M'))
ts = dt.timestamp()
datetime.fromtimestamp(ts)

type(dt)
type('a')
type(3)
type(3.3)

Python字典 結合LIST應用

max_points = [25,25,50,25,100]
assignments = ['ch 1','ch 2','quiz','ch 3','test']
students = {'#Max':max_points}

students['A']= [0]*len(max_points)
students['A'][2]=100
students['B']= [0]*5
students['C']= [2]*10
students['name']= [5]

students.keys()
students['#Max']
students['A']
students['B']
students['C']
students['name']

Python模組與套件


#模組匯入  #匯入到頂層命名空間(namespace)
dir()
import sys
import os.path
dir()
dir(os)
help(os)


#不安全的匯入方式
import os.path  as path
from os import path
from os.path import *
dir()

套件
模組就是一個檔案,而套件就是一個目錄!一個擁有著__init__.py檔案的目錄就會被Python視為一個套件,一個套件裡面收集了若干相關的模組或是套件,簡單來說套件就是個模組庫、函式庫。

假設我們自己寫了個套件叫做my_package:

my_package/
├── __init__.py
├── m1.py
├── m2.py
└── sub_package
    ├── __init__.py
    ├── m3.py
    └── m4.py

import m1
import sub_package
import sub_package.m3


python查看函數用法
print (FuncfionName.__oc__)

星期日, 3月 10, 2019

Python开发环境 重量級的資料科學相關套件

(1) 标准IDE: IDLE (内置,方便小巧)
https://www.python.org/

(2) 集成开发平台: Anaconda (支持多种操作系统,集成了主流的科学计算包,推荐初学者先安装这一个,后期需要其他第三方库再用pip等方式安装)
https://www.continuum.io/downloads

(3) 其他可自由选择PyCharm或Jupyter Notebook等


2.Python参考书籍和网站

(1) Python Crash Course: A Hands-On, Project-Based Introduction to Programming(Python编程 从入门到实践), 埃里克·马瑟斯 著

(2) SciPy科学计算ecosystem: https://www.scipy.org/

(3) Wes McKinney, Python for Data Analysis. 东南大学出版社. (英文影印本,中译版名为《利用Python进行数据分析》)




3.重量級的資料科學相關套件

Numpy 科學計算
重量級的資料科學相關套件(例如:Pandas、SciPy、Scikit-learn 等)都幾乎是奠基在 Numpy 的基礎上。因此學會 Numpy 對於往後學習其他資料科學相關套件打好堅實的基礎。
https://blog.techbridge.cc/2017/07/28/data-science-101-numpy-tutorial/
http://www2.nkfust.edu.tw/~shanhuen/PythonTutorialHtml/NumPy/NumPy1.html

Pandas 用於Excel
是一個基於Numpy的package,在處理數據方面非常的好用簡單,在學習pandas之前我們要先知道pandas的兩種特有的資料結構DataFrame與Series。

Matplotlib 用於繪圖
是Python的繪圖工具,你可以使用這些工具創建各種圖形,包括簡單的散點圖、直方圖,甚至是三維圖形,將你的資料轉成圖表,在python的數據分析中會經常使用Matplotlib完成數據可視化的工作!

SciPy
是以Numpy為基礎做科學、工程的運算處理的package,包含統計、優化、整合、線性代數、傅立葉轉換圖像等較高階的科學運算。