Ray's playground

 

Recipe 1.11. Checking Whether a String Is Text or Binary(Python Cookbook)

 1 >>> from __future__ import division
 2 >>> import string
 3 >>> text_chars = "".join(map(chr, range(32,127))) + "\n\r\b\b"
 4 >>> _null_trans = string.maketrans('''')
 5 >>> def istext(s, text_chars=text_chars, threshold=0.30):
 6     if "\0" in s:
 7         return False
 8     if not s:
 9         return True
10     t = s.translate(_null_trans, text_chars)
11     return len(t)/len(s) <= threshold
12 
13 >>> istext('adcdp')
14 True
15 >>> istext("")
16 True

 

posted on 2010-12-23 21:14  Ray Z  阅读(175)  评论(0编辑  收藏  举报

导航