Python Show-Me-the-Code 第 0012 题 替换敏感词

来源:互联网 发布:ubuntu ssh 远程登录 编辑:程序博客网 时间:2024/05/19 10:11

第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。

北京程序员公务员领导牛比牛逼你娘你妈lovesexjiangge

思路:跟0011题差不多,也是让用户输入词语,然后查找输入中是否含有敏感词,不同的就是把敏感词替换成星号然后输出。为了方便交互,使用了Python的CMD模块。

遇到个问题就是要计算敏感词字数时用到len函数,而参数要是unicode算出来的字数才是准确的,utf-8的话算出的会是字节的长度。


0012.替换敏感词.py

#!/usr/bin/env python#coding: utf-8import cmdimport 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 Trueif __name__ =="__main__":    cli = CLI()    cli.cmdloop()

这里写图片描述

1 0
原创粉丝点击