代码改变世界

随笔档案-2013年08月

Python urllib2 设置超时时间并处理超时异常

2013-08-01 21:20 by 江湖么名, 30119 阅读, 收藏,
摘要: 可以使用except: 捕获任何异常,包括SystemExit 和 KeyboardInterupt,不过这样不便于程序的调试和使用最简单的情况是捕获urllib2.URLErrortry: urllib2.urlopen("http://example.com", timeout = 1) except urllib2.URLError, e: raise MyException("There was an error: %r" % e) 以下代码对超时异常进行了捕获import urllib2 import socket class MyExcept 阅读全文

Python Unicode与中文处理(转)

2013-08-01 13:38 by 江湖么名, 979 阅读, 收藏,
摘要: Python Unicode与中文处理 python中的unicode是让人很困惑、比较难以理解的问题,本文力求彻底解决这些问题;1.unicode、gbk、gb2312、utf-8的关系;http://www.pythonclub.org/python-basic/encode-detail 这篇文章写的比较好,utf-8是unicode的一种实现方式,unicode、gbk、gb2312是编码字符集;2.python中的中文编码问题;2.1 .py文件中的编码 Python 默认脚本文件都是 ANSCII 编码的,当文件 中有非 ANSCII 编码范围内的字符的时候就要使用"编码 阅读全文

python 截取指定长度汉字

2013-08-01 13:35 by 江湖么名, 596 阅读, 收藏,
摘要: 这个方法不是很好,不知道有没有更好的方法def cut_hz(s, length): charstyle = chardet.detect(s) t = s[:length] try: unicode(t, charstyle['encoding']) except: t = s[:length-1] return t这样更好一点def cut_hz(s, length): charstyle = chardet.detect(s) uni_s = unicode(s, charstyle['encoding']) r... 阅读全文

python打印所有汉字

2013-08-01 13:20 by 江湖么名, 959 阅读, 收藏,
摘要: n=0for ch in xrange(0x4e00, 0x9fa6): print unichr(ch), n = n+1 if(n%50==0): print '\n'print n 阅读全文

python检测文件的MD5值

2013-08-01 11:54 by 江湖么名, 17122 阅读, 收藏,
摘要: python检测文件的MD5值MD5(单向散列算法)的全称是Message-Digest Algorithm 5(信息-摘要算法),经MD2、MD3和MD4发展而来。MD5算法的使用不需要支付任何版权费用。#python 检测文件MD5值#python version 2.6 import hashlibimport os,sys #简单的测试一个字符串的MD5值def GetStrMd5(src): m0=hashlib.md5() m0.update(src) print m0.hexdigest() pass #大文件的MD5值def GetFileMd5(fil... 阅读全文

python 字符集转换-灰常慢

2013-08-01 09:21 by 江湖么名, 388 阅读, 收藏,
摘要: 代码def toUni (text): str = text try: charstyle = chardet.detect(text) # print 'confidence: ', charstyle['confidence'] # 猜测精度 if ( charstyle['encoding'] == 'GB2312' ): str = text.decode( charstyle['encoding'], 'replace') elif ( charstyle['encoding 阅读全文

python版GetTickCount()

2013-08-01 08:53 by 江湖么名, 1753 阅读, 收藏,
摘要: time.clock()return the current processor time as a floating point number expressed in seconds.即返回一个浮点数,精度是毫秒例time.sleep(2.5)y = time.clock()print y - x返回值2.4998947806 阅读全文