Yixiaohan--0011及0012题,敏感词过滤及替换
2016-06-27 16:33
573 查看
Yixiaohan 第0011题及0012题,由于两题类似,并在一起
主要是用中文分词库 jieba(可使用 pip install jieba 直接安装),及os文件操作
代码如下(仅供参考,环境为python3.5X,Mac OS系统):
import os
import jieba
fil = []
f = open('filtered_words.txt','r')
for fword in f.readlines():
fil.append(fword.strip())#把敏感词文件的每一个词加入列表
f.close()
for fword in fil:
jieba.add_word(fword) #把每一个敏感词都确保成为一个词,而不会被分成两个或更多的词
while True:
userInput = input("请检测是否敏感词:")
lwords = jieba.lcut(userInput.strip())
for word in lwords:
if word in fil:
#0011题
filterKey = True
#0012题,循环检测并替换,确保每一个敏感词都会被替换,而不是只替换第一个
userInput = userInput.replace(word,'**')
continue
else:
filterKey = False
# print("Human Rights")
if filterKey:
print("Freedom")
print(userInput)
else:
print("Human Rights")
主要是用中文分词库 jieba(可使用 pip install jieba 直接安装),及os文件操作
代码如下(仅供参考,环境为python3.5X,Mac OS系统):
import os
import jieba
fil = []
f = open('filtered_words.txt','r')
for fword in f.readlines():
fil.append(fword.strip())#把敏感词文件的每一个词加入列表
f.close()
for fword in fil:
jieba.add_word(fword) #把每一个敏感词都确保成为一个词,而不会被分成两个或更多的词
while True:
userInput = input("请检测是否敏感词:")
lwords = jieba.lcut(userInput.strip())
for word in lwords:
if word in fil:
#0011题
filterKey = True
#0012题,循环检测并替换,确保每一个敏感词都会被替换,而不是只替换第一个
userInput = userInput.replace(word,'**')
continue
else:
filterKey = False
# print("Human Rights")
if filterKey:
print("Freedom")
print(userInput)
else:
print("Human Rights")
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法