Python日常小知识

一:python列表中的所有值转换为字符串,以及列表拼接成一个字符串

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

二:字符串转换

#字符串转为元组,返回:(1, 2, 3)
print tuple(eval("(1,2,3)"))
#字符串转为列表,返回:[1, 2, 3]
print list(eval("(1,2,3)"))
#字符串转为字典,返回:
print type(eval("{'name':'ljq', 'age':24}"))

三:创建文件并按行写入数据

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调用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
以上几种方式都可以调用API来执行动作,但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列表里的数据按行写入到txt文件

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

六:Python判断字符串是否为字母或者数字

严格解析:有除了数字或者字母外的符号(空格,分号,etc.)都会False
isalnum()必须是数字和字母的混合
isalpha()不区分大小写
str_1 = "123"
str_2 = "Abc"
str_3 = "123Abc"

#用isdigit函数判断是否数字
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判断是否数字和字母的组合
print(str_1.isalnum())    
Ture
print(str_2.isalnum())
Ture
print(str_1.isalnum())    
Ture

七:mysql数据库表到excel(仅支持.csv格式导出)

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访问网站示例

#coding:utf-8
import requests
# 访问的网页
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函数将字符转换为整数显示,chr函数将整数转换为字符显示

十:python接口开发

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

# 定义函数,参数是函数的两个参数,都是python本身定义的,默认就行了。
def application(environ, start_response):
    # 定义文件请求的类型和当前请求成功的code
    start_response('200 OK', [('Content-Type', 'text/html')])
    # environ是当前请求的所有数据,包括Header和URL,body,这里只涉及到get
    # 获取当前get请求的所有数据,返回是string类型
    params = parse_qs(environ['QUERY_STRING'])
    # 获取get中key为name的值
    name = params.get('name', [''])[0]
    no = params.get('no', [''])[0]
 
    # 组成一个数组,数组中只有一个字典
    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
 
 
# 定义函数,参数是函数的两个参数,都是python本身定义的,默认就行了。
def application(environ, start_response):
    # 定义文件请求的类型和当前请求成功的code
    start_response('200 OK', [('Content-Type', 'application/json')])
    # environ是当前请求的所有数据,包括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()))

未完待续。。。

(欢迎加入Python交流群:930353061。人生苦短,我用python!!!)

你可能感兴趣的:(Python日常小知识)