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
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