0%

Python练习册:0011

题目

    敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。

北京
程序员
公务员
领导
牛比
牛逼
你娘
你妈
love
sex
jiangge

分析

读取文本内容,添加到列表,获取输入,匹配即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
with open('filtered_words.txt','r') as f:
#读取内容到一个列表,并过滤每项中的'\n'
text = ''.join(f.readlines()).strip('\n').split()

while True:
#读取输入
line = input("> ")
#判断输入内容是否含有敏感词
if any( [words in line for words in text]):
print('Freedom')
else:
print('Human Rights')

扩展

当敏感词列表非常多的时候这示例就不是那么好用了,主要原因在于字符匹配算法太低效,可以尝试:

参考

欢迎关注我的其它发布渠道