Python Show-Me-the-Code 第 0012 题 替换敏感词
2015-05-21 11:10
417 查看
第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。
思路:跟0011题差不多,也是让用户输入词语,然后查找输入中是否含有敏感词,不同的就是把敏感词替换成星号然后输出。为了方便交互,使用了Python的CMD模块。
遇到个问题就是要计算敏感词字数时用到len函数,而参数要是unicode算出来的字数才是准确的,utf-8的话算出的会是字节的长度。
0012.替换敏感词.py
北京 程序员 公务员 领导 牛比 牛逼 你娘 你妈 love sex jiangge
思路:跟0011题差不多,也是让用户输入词语,然后查找输入中是否含有敏感词,不同的就是把敏感词替换成星号然后输出。为了方便交互,使用了Python的CMD模块。
遇到个问题就是要计算敏感词字数时用到len函数,而参数要是unicode算出来的字数才是准确的,utf-8的话算出的会是字节的长度。
0012.替换敏感词.py
#!/usr/bin/env python #coding: utf-8 import cmd import sys # 存放敏感词文件的路径 filtered_words_filepath = '/home/bill/Desktop/filtered_words.txt' class CLI(cmd.Cmd): def __init__(self): # 初始化,提取敏感词列表 cmd.Cmd.__init__(self) self.intro = 'Filtered Words Detective' self.words = map(lambda i: i.strip('\n').decode('utf-8'), open(filtered_words_filepath).readlines()) self.prompt = "> " # define command prompt def default(self, line): line = line.decode('utf-8') for i in self.words: line = line.replace(i, len(i)*'*') print line def do_quit(self, arg): exit() return True if __name__ =="__main__": cli = CLI() cli.cmdloop()
相关文章推荐
- Python Show-Me-the-Code 第 0022 题 批量图片处理2
- 将“talk is cheap show me the code”中的空格替换为“&&&”
- Python Show-Me-the-Code 第 0010 题 生成验证码图片
- Python Show-Me-the-Code 第 0007 题 统计代码行数(注释,空行,总行数)小程序
- show me the code --python25道练习题
- python 操作 redis --show me the code 0003
- Python Show-Me-the-Code 第 0001 题 生成激活码
- Python Show-Me-the-Code 第 0004 题 统计单词
- python show-me-the-code 第0010题
- Show me the code之Python练习册Q23-留言板
- github/python/ show me the code 25题(二)
- Show me the code之Python练习册 Q10 生成验证码
- python之 heapq -- show me the code 0006
- python show-me-the-code 第0004
- python show-me-the-code 第0012题
- Python Show-Me-the-Code 第 0009 题 提取网页中的超链接
- python之os -- show me the code 0005
- Show me the code之Python练习册 Q11~12 关键词过滤
- python操作mysql关系数据库 show me the code 0001-0002
- 以Python的项目show-me-the-code为例,说明本地git与github