首页 技术 正文
技术 2022年11月14日
0 收藏 762 点赞 3,805 浏览 851 个字

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


任务:

  给定一个需要保留的字符串的集合,构建一个过滤函数,并可将其应用于任何字符串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))) + '\n\t\r\b'
_null_trans = string.maketrans('','')
def istext(s,textcharacters = text_characters,threshold = 0.30):
if '\0' in s:
return False
if not s:
return True
t = s.translate(_null_trans,text_characters)
return len(t)/len(s) <= threshold
print istext('')

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,918
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,444
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,255
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,069
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,701
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,741