《Python CookBook2》 第一章 文本

过滤字符串中不属于指定集合的字符


任务:

  给定一个需要保留的字符串的集合,构建一个过滤函数,并可将其应用于任何字符串s,函数返回一个s的拷贝,该拷贝只包含指定字符集合中的元素。 

解决方案:  

import string
allchars = string.maketrans('','')  #all chars table
def makefilter(keep):
    delchars = allchars.translate(allchars,keep)
    def thefilter(s):
        return s.translate(allchars,delchars)#delchars是要删除的字符串list内容
    return thefilter
if __name__ == "__main__":
    just_vowels = makefilter('aeiouy')
    print just_vowels('i love python')
    print just_vowels('wwwwwwwwww')

  

检查一个字符串是文本还是二进制


任务:

  在 python中,普通字符串既可以容纳文本,也可以容纳任意的字节,现在需要探知一个字符串中的数据究竟是文本还是二进制。 

解决方案: 

  

from __future__ import division
import string
text_characters = ''.join(map(chr,range(32,127))) + '
	
'
_null_trans = string.maketrans('','')
def istext(s,textcharacters = text_characters,threshold = 0.30):
    if '' in s:
        return False
    if not s:
        return True
    t = s.translate(_null_trans,text_characters)
    return len(t)/len(s) <= threshold
print istext('1101111111')

目前还是不是很懂这个方法,代码的结构还是在学习适应中

 

原文地址:https://www.cnblogs.com/wuzhiming/p/3935261.html