学习一下python,这里对python的基础知识做一个整理。似等了一百年忽而明白,即使再见面,成熟地表演,不如不见。
python的一些应用
一、类似于java中的MessageFormat用法
word = "{0} love {1}" wordList = ('huhx', 'linux') print(word.format(*wordList)) print(word.format('huhx', 'linux')) str_word = "{name} love {lover}" wordMap = dict(name='huhx', lover='linux') print(str_word.format(name='huhx', lover='linux')) print(str_word.format(**wordMap)) print(str_word.format_map(wordMap))
打印结果都是:huhx love linux
二、关于正则中贪心匹配的理解
import re data = 'Thu Feb 15 17:46:04 2007::uzifzf@dpyivihw.gov::1171590364-6-8' print(re.search('d+-d+-d+', data).group()) # 1171590364-6-8 print(re.match('.+d+-d+-d+', data).group()) # Thu Feb 15 17:46:04 2007::uzifzf@dpyivihw.gov::1171590364-6-8 print(re.match('.+(d+-d+-d+)', data).group(1)) # 4-6-8 print(re.match('.+?(d+-d+-d+)', data).group(1)) # 1171590364-6-8
三、python中简单的json请求
import http.client import json conn = http.client.HTTPConnection("hostname") data = { 'TellerId': '***', 'Password': '***' } payload = json.dumps(data) headers = { 'content-type': "application/json" } conn.request("POST", "/mweb/login.do", payload, headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8"))
四、python中简单的mysql连接
首先可以通过:pip install pymysql安装pymysql。
import pymysql db = pymysql.connect("localhost","root","pass","database", charset='utf8') cur = db.cursor() cur.execute('select * from puser') for i in cur.fetchall(): print(str(i)) db.close()
五、python中使用sftp连接的简单使用
首先可以通过:pip install paramiko安装sftp的支持
import paramiko host = 'hostname' port = 22 user = 'root' passwd = 'password' # 创建SSH对象 ssh = paramiko.SSHClient() # 允许连接不在know_hosts文件中的主机 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接服务器 ssh.connect(hostname=host, port=port, username=user, password=passwd) # 执行命令 stdin, stdout, stderr = ssh.exec_command('ls -al') # 获取命令结果 result = stdout.read() print(result) # 关闭连接 ssh.close()
六、python简单连接操作redis
首先启动redis服务,然后下载python的redis包:pip install redis。
import redis r = redis.Redis(host='127.0.0.1',port=6379) r.set('name', 'linux') print(r.get('name')) # linux
七、python简单的dom对xml的解析
from xml.dom.minidom import parse import xml.dom.minidom DOMTree = xml.dom.minidom.parse("huhx.xml") collection = DOMTree.documentElement persons = collection.getElementsByTagName('person') for person in persons: if person.hasAttribute('name'): print('my name is %s: ' % person.getAttribute('name')) age = person.getElementsByTagName('age')[0].childNodes[0].data address = person.getElementsByTagName('address')[0].childNodes[0].data print('age = %d, address = %s.' % (int(age), address))
测试的huhx.xml文件如下:
<persons> <person name="huhx"> <age>12</age> <address>wuhan</address> </person> <person name="linux"> <age>1</age> <address>hubai</address> </person> </persons>
运行的结果如下:
my name is huhx: age = 12, address = wuhan. my name is linux: age = 1, address = hubai.
八、python中csv文件的读写
csv文件可以在excel表中建立数据,最后保存的时候存为csv格式的文件。
- 先看一个读取csv文件的内容,测试的huhx.csv文件内容如下:
import csv csvFile = open('huhx.csv', 'r') reader = csv.reader(csvFile) for item in reader: for subItem in item: print(subItem, end=" ") print()
运行的结果如下:
姓名 年龄 地址 huhx 23 china linux 24 hubai liuling 21 wuhan
- python写入内容到csv文件
import csv fileHeader = ['username', 'age', 'address'] data1 = ['huhx', 342, 'hubai'] data2 = ['linux', 56, 'wuhan'] data3 = ['tomhu', 44, 'china'] csvFile = open('huhx.csv', 'a') writer = csv.writer(csvFile) # writer.writerow(fileHeader) # writer.writerow(data1) # writer.writerow(data2) # writer.writerow(data3) writer.writerows([fileHeader, data1, data2, data3]) csvFile.close()
九、python中的两个list相加
list1, list2 = [2, 3, 4], [3, 4, 6] tempList = list1 + list2 print(tempList) # [2, 3, 4, 3, 4, 6] tempList = list() for x, y in zip(list1, list2): tempList.append(x + y) print(tempList) # [5, 7, 10] list1.extend(list2) print(list1) # [2, 3, 4, 3, 4, 6]
十、python中的列表生成式
>>> [x * x for x in range(1, 5) if x % 2 ==0] [4, 16] >>> [x * x for x in [1, 3, 4] if x % 2 ==0] [16] >>> [x * 2 for x in 'abc' if x == 'a'] ['aa']