您的位置:首页 > 编程语言 > Python开发

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

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

北京
程序员
公务员
领导
牛比
牛逼
你娘
你妈
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()


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: