Python日常小知識

一:python列表中的所有值轉(zhuǎn)換為字符串,以及列表拼接成一個字符串

> ls1 = ['a', 1, 'b', 2] 
> ls2 = [str(i) for i in ls1]
> ls2 ['a', '1', 'b', '2'] 
>ls3 = ''.join(ls2) 
> ls3 'a1b2'

二:字符串轉(zhuǎn)換

#字符串轉(zhuǎn)為元組,返回:(1, 2, 3)
print tuple(eval("(1,2,3)"))
#字符串轉(zhuǎn)為列表,返回:[1, 2, 3]
print list(eval("(1,2,3)"))
#字符串轉(zhuǎn)為字典,返回:<type 'dict'>
print type(eval("{'name':'ljq', 'age':24}"))

三:創(chuàng)建文件并按行寫入數(shù)據(jù)

with open("%s\sitemap%d.txt" % (self.path,file_num), "a") as f:
    for i in url_list:
        u  = str(i) + '\n'
        f.writelines(u)
    f.close()

四:Python調(diào)用API接口的幾種方式

方式一:
import urllib2, urllib
github_url = 'https://api.github.com/user/repos'
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, github_url, 'user', '***')
auth = urllib2.HTTPBasicAuthHandler(password_manager) # create an authentication handler
opener = urllib2.build_opener(auth) # create an opener with the authentication handler
urllib2.install_opener(opener) # install the opener...
request = urllib2.Request(github_url, urllib.urlencode({'name':'Test repo', 'description': 'Some test repository'})) # Manual encoding required
handler = urllib2.urlopen(request)
print handler.read()

方式二:
import urllib, httplib2
github_url = ""
h = httplib2.Http(".cache")
h.add_credentials("user", "******")
data = urllib.urlencode({"name":"test"})
resp, content = h.request(github_url, "POST", data)
print content

方式三:
import pycurl, json
github_url = ""
user_pwd = "user:*****"
data = json.dumps({"name": "test_repo", "description": "Some test repo"})
c = pycurl.Curl()
c.setopt(pycurl.URL, github_url)
c.setopt(pycurl.USERPWD, user_pwd)
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, data)
c.perform()

方式四:
import requests, json
github_url =""
data = json.dumps({'name':'test', 'description':'some test repo'})
r = requests.post(github_url, data, auth=('user', '*****'))
print r.json
以上幾種方式都可以調(diào)用API來執(zhí)行動作,但requests這種方式代碼最簡潔,最清晰,建議采用。

例子:
import requests
reqs = requests.session()
reqs.keep_alive = False
import json
url = "http://127.0.0.1:9999/download/login" #接口地址
data = {"user": "****", "password": "*****"}
r = requests.post(url, data=data)
print r.text
print type(r.text)
print json.loads(r.text)["user_id"]  

五:將list列表里的數(shù)據(jù)按行寫入到txt文件

with open(file_num, "w") as f:
    for ip in url_list:
        f.write(ip)
        f.write('\n')
    f.close()

六:Python判斷字符串是否為字母或者數(shù)字

嚴(yán)格解析:有除了數(shù)字或者字母外的符號(空格,分號,etc.)都會False
isalnum()必須是數(shù)字和字母的混合
isalpha()不區(qū)分大小寫
str_1 = "123"
str_2 = "Abc"
str_3 = "123Abc"

#用isdigit函數(shù)判斷是否數(shù)字
print(str_1.isdigit())
Ture
print(str_2.isdigit())
False
print(str_3.isdigit())
False

#用isalpha判斷是否字母
print(str_1.isalpha())    
False
print(str_2.isalpha())
Ture    
print(str_3.isalpha())    
False

#isalnum判斷是否數(shù)字和字母的組合
print(str_1.isalnum())    
Ture
print(str_2.isalnum())
Ture
print(str_1.isalnum())    
Ture

七:mysql數(shù)據(jù)庫表到excel(僅支持.csv格式導(dǎo)出)

import config
table = config.KEY_CSV
key = config.KEYWORD_TABLE
mysql_conn = StoreMysqlPool(**config.DB_CONTNET)
data = mysql_conn.query("select keyword, rank, real_url, fd,pcpv,mpv,allpv,rst from {} where allpv>0 and rank != 0 ".format(key))
import csv

with open('{}'.format(table.encode("gbk")), 'wb') as csvfile:
    spamwriter = csv.writer(csvfile)
    spamwriter.writerow(['keyword', 'rank', 'real_url', 'fd', 'pcsv', 'msv', 'allsv','rst(1收錄,2未收錄)'])
    for each in data:
        spamwriter.writerow([each[0], each[1], each[2], each[3], each[4], each[5], each[6], each[7]])
print("end")

八:利用代理ip訪問網(wǎng)站示例

#coding:utf-8
import requests
# 訪問的網(wǎng)頁
url = "https://www.tissotwatches.com/"#
# 使用的代理ip地址
proxy = {"http": '169.235.24.133:8080'}#
# 使用方法一
rsp = requests.get(url=url, proxies=proxy)
print(rsp.text)
print("$"*60)#
# 使用方法二
# rsp = requests.request("get", url, proxies=proxy)
# print(rsp.text)

九:輸出字母(輸出a-k字母)

for i in range(ord('a'), ord('k') + 1):
    m = chr(i)
    print m
    
ps:ord函數(shù)將字符轉(zhuǎn)換為整數(shù)顯示,chr函數(shù)將整數(shù)轉(zhuǎn)換為字符顯示

十:python接口開發(fā)

get請求方式
# coding:utf-8
import json
from urlparse import parse_qs
from wsgiref.simple_server import make_server

# 定義函數(shù),參數(shù)是函數(shù)的兩個參數(shù),都是python本身定義的,默認(rèn)就行了。
def application(environ, start_response):
    # 定義文件請求的類型和當(dāng)前請求成功的code
    start_response('200 OK', [('Content-Type', 'text/html')])
    # environ是當(dāng)前請求的所有數(shù)據(jù),包括Header和URL,body,這里只涉及到get
    # 獲取當(dāng)前get請求的所有數(shù)據(jù),返回是string類型
    params = parse_qs(environ['QUERY_STRING'])
    # 獲取get中key為name的值
    name = params.get('name', [''])[0]
    no = params.get('no', [''])[0]
 
    # 組成一個數(shù)組,數(shù)組中只有一個字典
    dic = {'name': name, 'no': no}
 
    return [json.dumps(dic)]
 
if __name__ == "__main__":
    port = 5088
    httpd = make_server("0.0.0.0", port, application)
    print "serving http on port {0}...".format(str(port))
    httpd.serve_forever()
--------------------------------------------
post請求方式
# coding:utf-8
 
import json
from wsgiref.simple_server import make_server
 
 
# 定義函數(shù),參數(shù)是函數(shù)的兩個參數(shù),都是python本身定義的,默認(rèn)就行了。
def application(environ, start_response):
    # 定義文件請求的類型和當(dāng)前請求成功的code
    start_response('200 OK', [('Content-Type', 'application/json')])
    # environ是當(dāng)前請求的所有數(shù)據(jù),包括Header和URL,body
 
    request_body = environ["wsgi.input"].read(int(environ.get("CONTENT_LENGTH", 0)))
    request_body = json.loads(request_body)
 
    name = request_body["name"]
    no = request_body["no"]
 
    # input your method here
    # for instance:
    # 增刪改查
 
    dic = {'myNameIs': name, 'myNoIs': no}
 
    return [json.dumps(dic)]
 
 
if __name__ == "__main__":
    port = 6088
    httpd = make_server("0.0.0.0", port, application)
    print "serving http on port {0}...".format(str(port))
    httpd.serve_forever()

---------------------------------------------------
示例:flask接口
# -*- coding: utf-8 -*-
from flask import Flask
app = Flask(__name__)

@app.route('/login/')
def demo():
    return 'logion'


if __name__ == '__main__':
    app.run(host='127.0.0.1')
訪問:http://127.0.0.1:5000/login/

十一: 格式化日期:

import time
# 格式化成2016-03-20 11:45:39形式
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

# 格式化成Sat Mar 28 22:24:24 2016形式
print (time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))

未完待續(xù)。。。

(歡迎加入Python交流群:930353061。人生苦短,我用python!?。。?/h5>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容