filter python

filter的作用是过滤

在python2中filter直接返回过滤后的结果

而python3中filter返回迭代器,有助于节约内存:

#filter(function, iterable)
x = filter(lambda x: x % 2 == 0, range(10))
print(" ".join(str(i) for i in x))  # 2 4 6 8

 

在文本处理中:

import re
import jieba
line="James's another name詹姆斯代号007是个大骗子!"
line="".join(char for char in filter(lambda x:x not in "是个",line)) #'James詹姆斯代号007大骗子!'
words=jieba.lcut(line)
rule=re.compile(r"^[\u4e00-\u9fa5]+$") #只保留中文
line_words=[word for word in words if re.search(rule, word) ] #['詹姆斯', '代号', '大骗子']

line="第一章猴子大战吕布第二章吕布归顺董卓。。。第十五章人生梦如路长"
line=re.split(r'第.{1,3}章',line)[1:] #['猴子大战吕布', '吕布归顺董卓。。。', '人生梦如路长']

#过滤掉非英文单词和非数字和一些非指定的标点符号
line="James's another name詹姆斯代号007是个大骗子!"
line = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", line) 
line.strip().lower() #"james's another name 007"

 

 

 

posted @ 2019-11-26 20:24  熊猫blue  阅读(152)  评论(0)    收藏  举报