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
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
相关文章推荐
- Recipe 1.3. Testing Whether an Object Is String-like(Python Cookbook)
- Recipe 1.8. Checking Whether a String Contains a Set of Characters(Python Cookbook)
- Recipe 1.7. Reversing a String by Words or Characters(Python Cookbook)
- Recipe 1.10. Filtering a String for a Set of Characters(Python Cookbook)
- Recipe 1.5. Trimming Space from the Ends of a String(Python Cookbook)
- Python Cookbook 第二版 汉化版 [Recipe 1.3] 测试一个对象是否为 String-like 对象
- Recipe 1.1. Processing a String One Character at a Time(Python Cookbook)
- Python Cookbook 第二版 汉化版 [Recipe 1.3] 测试一个对象是否为 String-like 对象
- Python Cookbook 第二版 汉化版 [Recipe 16.4] 将参数与函数关联起来(Currying)
- Python Cookbook 第二版 汉化版 [Recipe 1.2] 字符与其对应的数字编码之间的转换
- Python Cookbook 第二版 汉化版 [Recipe 1.8] 检测字符串是否包含特定的字符集合
- Python Cookbook 第二版 汉化版 [Recipe 16.4] 将参数与函数关联起来(Currying)
- Recipe 1.9. Simplifying Usage of Strings' translate Method(Python Cookbook)
- Python Cookbook 第二版 汉化版 [Recipe 1.1] 逐个处理字符串中的各个字符
- rsync - Linux Security Cookbook - Recipe 1.16 Integrity Checking with rsync
- Python Cookbook 第二版 汉化版 [Recipe 1.1] 逐个处理字符串中的各个字符
- 判断是否为完全二叉树 Check whether a binary tree is a complete tree or not
- rsync - Linux Security Cookbook - Recipe 1.6 Remote Integrity Checking
- Check whether a given Binary Tree is Complete or not 解答
- Recipe 1.4. Aligning Strings(Python Cookbook)