python小程序-0010

第10题:敏感词文本文件 filtered_words.txt,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。

#!/usr/bin/env python3
# -*- coding : utf-8 -*-

import cmd
import sys

class words(cmd.Cmd):
    def __init__(self,path):
        self.path = path
        self.filterwords = []
        cmd.Cmd.__init__(self,self.path)
        with open(self.path,'r') as f:
            for line in f.readlines():
                line = line.strip('\n')
                self.filterwords.append(line)
        self.intro = "Please enter your words:"
        self.prompt = "> "

    def default(self,word):
        #print( self.filterwords)
        for i in self.filterwords:
            word = word.replace(i,len(i)*'*')
        print(word)

    def do_exit(self,arg):
        sys.exit()

if __name__ == "__main__":
    path = input("Please input filter_words_text path:")
    cc = words(path)
    cc.cmdloop()

你可能感兴趣的:(python)