您的位置:首页 > 编程语言 > Python开发

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

2010-12-23 21:14 489 查看
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
t = s.translate(_null_trans, text_chars)
return len(t)/len(s) <= threshold

>>> istext('adcdp')
True
>>> istext("")
True
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐