小程序需求说明
敏感词文本文件 filtered_words.txt,里面的内容为以下内容:
北京程序员公务员领导牛比牛逼你娘你妈lovesexjiangge当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。
思路及程序编写
###流程敲定:# 1. 用户输入一句话# 2. 检查里面没有没有敏感词汇# 2.1 将敏感词汇读取出来。使用readline(),或者直接使用文件管理器。# 2.2 检测用户输入是否含有敏感词 in# 3.判断是否有后进行反应##user_input=input('Please say something:')print(user_input)for filter_word in open('filtered_words.txt'): #这里碰到一个东西就是,使用open()文件迭代器的方法,会自动在读取的对象后面增加一个跨行符号 , #所以这里需要一个rstrip()去掉右边的跨行符。 if filter_word.rstrip() in user_input: print('Freedom!') breakelse: print('Human Rights!')#如果不使用跨行符,那么结果就是 filter_word in user_input 永远是false, Freedom不会被打印。#下面示范没有rstrip()的形式。print('这是分割线,哦啦啦啦啦')user_input=input('Please say something:')print(user_input)for filter_word in open('filtered_words.txt'): if filter_word in user_input: print('Freedom!') breakelse: print('Human Rights!')执行后的输出
Please say something:sexysexyFreedom!这是分割线,哦啦啦啦啦Please say something:sexysexyHuman Rights!小结(always continue…)
整个小程序的重点:
1.文件的读取。
这里我们使用了文件迭代器:
for col in open('文件名')在使用文件迭代器的时候,我们需要直到,每次迭代是按照行来读取,并且读取的内容后面会有一个跨行符号。
移除跨行符号我们有多种方法,常见的有:
- 分片
- strip,lstrip,rstrip
这里我们推荐rstrip方法,因为分片即使最后没有跨行符,也会让其少一截。
#使用分片去除跨行符(空格同理) s='abcd' print(s)abcd print(s[:-1])abcd s='abcd' print(s[:-1])abc 2.判断时候含有敏感词
这个时候就用到了成员测试in 就可以轻松解决。
小程序其他方案
1.读取文件方面,我们还可以readline(),不过文件迭代器是按照行读取文件的最方便的方法。
小程序测试来自于













