有用python代码片断
1 日期与字符串转换
#convert a string to a datetime object
from datetime import datetime
date_obj = datetime.strptime(‘May 29 2015 2:45PM’, ‘%B %d %Y %I:%M%p’)
#converting datetime object to a formatted string
from datetime import datetime
date_obj = datetime.now()
date_string = date_obj.strftime(‘%B %d %Y %I:%M%p’)
2 网上数据更新host文件
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys,os
import urllib.request,re
if __name__ == ‘__main__’:
print(‘谷歌host修改脚本\n数据:http://www.360kb.com/kb/2_122.html’)
#load host from 360kb
htmlH = urllib.request.urlopen(‘http://www.360kb.com/kb/2_122.html’)
html = htmlH.read().decode(‘utf-8′)
reg = r’#base services.*#google hosts 2015 end’
hostHtmlRe = re.search(reg, html, re.S)
hostHtml = hostHtmlRe.group()
hostHtml = hostHtml.replace(‘ ‘,’ ‘)
hostHtml = hostHtml.replace(‘‘, ”)
hostHtml = hostHtml.replace(‘‘, ”)
hostStr = hostHtml.replace(‘
‘,”)
#write host file
f = open(‘C:\\Windows\\System32\\drivers\\etc\\hosts’, ‘r+’)
hostOld = f.read()
reg = re.compile(r’\r\n#google=.*#google hosts 2015 end’, re.S)
hostNew = re.sub(reg, ”, hostOld)
hostNew = hostNew + ‘\r\n#google===========================\r\n’ + hostStr
#安全起见,不修改account相关
reg = re.compile(r’account’, re.S)
hostNew = re.sub(reg, ‘OOXXaccount’, hostNew)
print(hostNew)
f.seek(0)
f.write(hostNew)
f.close()
print(‘ok’)
3 执行外部命令
>>> import subprocess
>>> subprocess.call([‘mkdir’, ‘test’])
0
>>> output = subprocess.check_output([‘ls’, ‘-l’])
>>> print(output)
b’total 8\ndrwxrwxr-x 4 nagios nagios 4096 Jan 12 16:29 plugin\ndrwxrwxr-x 3 nagios nagios 4096 Jan 5 14:59 pysrc\n’
>>> print(output.decode(‘utf-8’))
total 8
drwxrwxr-x 4 nagios nagios 4096 Jan 12 16:29 plugin
drwxrwxr-x 3 nagios nagios 4096 Jan 5 14:59 pysrc
4 将长字符串中含有word的词改为对应字母个数的**
def censor4(texts,word):
text=texts.split()
s=’*’*len(word)
list=map(lambda x: x if x!=word else s ,text)
return ‘ ‘.join(list)
if __name__==’__main__’:
word=’everyone’
texts=”one hello everyone onea there are one boy and one girl one”
print (censor4(texts,word))
输出:
one hello ******** onea there are one boy and one girl one
5 Oracle库中的表生成文本
#!/usr/local/python3.4.5/bin/python3
# coding=utf-8
import os
import csv
import cx_Oracle
from pprint import pprint
con = cx_Oracle.connect(‘hr/hr@prod’)
cursor = con.cursor()
cursor.execute(“SELECT OBJECTID,SDE.ST_ASTEXT(SHAPE) FROM reas.GR_AREA t WHERE T.STATUS_CD <> ‘2’”)
f =open(‘GR_AREA1.AVL’,’w’,encoding=’utf8′,newline=”)
writer = csv.writer(f,delimiter=chr(1),quoting=csv.QUOTE_NONE)
for row in cursor:
writer.writerow(row)
f.close()
近期评论