敏感词文本文件: filtered_words.txt
里面的内容如下:
北京 程序员 公务员 领导 love ...
当用户输入敏感词语:
则打印出 Freedom
否则打印出 Human Rights
Sensitive word detection:
cmd模块是python中包含的一个公共模块,用于交互式shell和其它命令解释器等。下面我们利用cmd模块帮助实现敏感词检测:
下面的代码可以直接复制,修改文件路径即可实现
import cmd
#文件存放路径,这里改为你电脑中的文件存放路径
filer_path='C:/workspace/VS Code training/test6-Sensitive word detection/filtered_words.txt'
class Cli(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
#获取输入
self.intro='请输入:'
#读取文本文件内容,放入列表
with open(filer_path,'r',encoding='utf-8') as fr:
frr=fr.readlines()
self.words=list(map(lambda i: i.strip('\n'),frr)) #重要!
#输入提示符,可省略
self.prompt='>>>'
def default(self,line):
if any([i in line for i in self.words]):
print('Freedom')
else:
print('Human Rights')
if __name__=='__main__':
cli=Cli()
cli.cmdloop()