第 0011 题: 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。
北京
程序员
公务员
领导
牛比
牛逼
你娘
你妈
love
sex
jiangge
第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。
Answer:
-
这两道题其实很类似,只是最后的操作不同
首先你要建立一个需要敏感词库,即读取 filtered_words.txt内的内容
这时候你需要的就是将python看起来是一整个文本的内容,分割为一个个单词
有了敏感词列表后,判断敏感词列表中的敏感词是否在你的输入中
0011:如果有 跳出 输出Freedom
0012:如果有 替换为*号
-
主要问题是如何建立敏感词库
这里可以看到txt文件中一个敏感词占一行
所以采用了readlines()这个方法,去掉末尾的换行符号,存入列表
-
0011:设立了一个flag标志位,因为不设标志位,每个敏感词就会输出一个“Freedom”或者“Human Rights”
0012:用了replace,但是记住replace是生成一个新的字符串而不是对原本进行修改
-
代码实现
#0011
#coding:utf-8
import os
os.chdir(r'C:\Users\Alex.hasee-PC\Desktop\pythonprogram')
def getfilter():
file=open('filtered_words.txt')
words=[]
for w in file.readlines():
words.append(w.strip('\n'))
return words
scan=raw_input('>>>')
filterwords=getfilter()
flag=0
for i in filterwords:
if i in scan:
flag=1
break
else:
flag=0
if flag==1:
print "Freedom"
elif flag==0:
print "Human Rights"
#0012
#coding:utf-8
import os
os.chdir(r'C:\Users\Alex.hasee-PC\Desktop\pythonprogram')
def getfilter():
file=open('filtered_words.txt')
words=[]
for w in file.readlines():
words.append(w.strip('\n'))
return words
scan=raw_input('>>>')
filterwords=getfilter()
for w in filterwords:
scan=scan.replace(w,'*'*len(w))
print "Filter:%s" %scan
-