python时分复用_python经常复用的程序片段记载

这篇博客介绍了Python编程中的一些基础操作,包括如何处理命令行参数,进行文件错误捕捉,利用urllib和urllib2发送POST请求,以及时间的获取和格式化。此外,还涉及到了数据去重方法和eval()函数在处理特定字符串时可能出现的问题及解决方案。
摘要由CSDN通过智能技术生成

1 有输入参数

import sys, os

if len(sys.argv) < 3:

print 'input invalid'

exit(1)

a = sys.argv[1]

b = sys.argv[2]

if not a.isdigit() or not b.isdigit():

print 'input is not digit'

exit(1)

2 打开文件错误捕捉

try:

f1 = open(str(i))

except IOError, e:

print 'cannot open file ' + str(i)

i += 1

continue

line = f1.readline()

dic = eval(line)

f1.close()

3  用urllib和urllib2发送post请求

body = urllib.urlencode({

'token':token,

'task':'{"TaskName":"testScipt"}'})

returnedReq = urllib2.Request(

url = 'http://www.test.com/',

data = body)

returnedResult = urllib2.urlopen(returnedReq).read()

returnedResult = returnedResult.strip()

print returnedResult

4 操作excel

import xlrd

data = xlrd.open_workbook('test.xlsx')

table = data.sheets()[0] #选择第一个工作区

cols = table.col_values(0) #选择第一列

print len(cols)

5  使用eval()或ast.literal_eval() 出现错误

NameError: name ‘total_count’ is not defined或ValueError: malformed string

比如原始字符串是 str = '{"name":"jgy","age":null}'

转为字典时会发现null不是一个字符串,就当做变量,但是没有定义(python认可的是Null True False 注意第一个字母大写),所以出错,相应的实际过程中可能还会到 ‘true’ is not defined, ‘false’ is not defined类似的等等。

既然没定义,在前面定义一下就行了,比如自己定义 null = 'null',  true = 'true'..

还有个想法,可以用正则把冒号后面的不是数字也没加引号的value值给加上引号。

6 时间

获取最简洁日期格式:

>>>time.strftime('%Y-%m-%d',time.localtime(time.time()))

'2013-07-04'

获取上一秒时间:

time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time() - 1))

将一个字符串时间转为python时间格式

str1 = '2013-06-03 20:07:41'

str2 = '2013-06-03 20:08:43'

time1= time.strptime(str1,"%Y-%m-%d %H:%M:%S") #time1 is time_struct type

time1= time.strptime(str2,"%Y-%m-%d %H:%M:%S")

#now we wanna to 取得time1和time2的时间差

#需要转为datetime,然后使用datetime的timedelta方法

datetime1 = datetime.datetime(*time1[:6])

datetime2 = datetime.datetime(*time2[:6])

datedelta = datetime2 - datetime1

print datedelta

#datetime.timedelta(0, 62) #后面是秒数

seconds = delta.seconds #获取int型秒数

7 海量数据去重

>>> a = [11,22,33,44,11,22]

>>> b = set(a)

>>> b

set([33, 11, 44, 22])

>>> c = [i for i in b]

>>> c

[33, 11, 44, 22]

8

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值