python中哪些词是敏感字词_第1.7题: Python敏感词检测

本文介绍了Python中如何进行敏感词检测,通过读取敏感词文本文件并利用find()、strip()等方法处理用户输入,当检测到敏感词时输出"Freedom",否则输出"Human Rights"。还讨论了map()函数的使用,并提醒在使用map()时注意数据保存的问题。
摘要由CSDN通过智能技术生成

题目来自:Python 练习册。题目1.7:敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。

查看更多于本人博客:iii.run

Python find()方法

描述

Python find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。

语法

find()方法语法:

str.find(str, beg=0, end=len(string))

参数

str -- 指定检索的字符串

beg -- 开始索引,默认为0。

end -- 结束索引,默认为字符串的长度。

返回值

如果包含子字符串返回开始的索引值,否则返回-1。

实例

以下实例展示了find()方法的实例:

info = 'abca'

print info.find('a')##从下标0开始,查找在字符串里第一个出现的子串,返回结果:0

info = 'abca'

print info.find('a',1)##从下标1开始,查找在字符串里第一个出现的子串:返回结果3

info = 'abca'

print info.find('333')##返回-1,查找不到返回-1

Python strip()方法

描述

Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)。

语法

strip()方法语法:

str.strip([chars]);

参数

chars -- 移除字符串头尾指定的字符。

返回值

返回移除字符串头尾指定的字符生成的新字符串。

实例

以下实例展示了strip()函数的使用方法:

str = "0000000this is string example....wow!!!0000000";

print str.strip( '0' );

以上实例输出结果如下:

this is string example....wow!!!

Python map()方法

描述

很简单,第一个参数接收一个函数名,第二个参数接收一个可迭代对象。

语法

map(f, iterable)

基本上等于:

[f(x) for x in iterable]

实例

>>> def add100(x):

... return x+100

...

>>> hh = [11,22,33]

>>> map(add100,hh)

[111, 122, 133]

参考代码

#coding: utf-8

import cmd

# 存放敏感词文件的路径

filtered_words_filepath = 'd:/filtered_words.txt'

class CLI(cmd.Cmd):

def __init__(self): #初始基础类方法

cmd.Cmd.__init__(self) # 初始化,提取敏感词列表

self.intro = 'Python敏感词检测:' #输出欢迎信息

f = open(filtered_words_filepath)

self.words = list(map(lambda i: i.strip('\n'), f.readlines()))

self.prompt = ">>> " # 定义提示符

def default(self, line):

if any([i in line for i in self.words]):

print ('Freedom')

else:

print ('Human Rights')

def do_quit(self, arg):

exit()

return True

if __name__ =="__main__":

cli = CLI()

cli.cmdloop()

其实这个地方出现过一个错误,map()形成的iterable是一次性的。

也就是如果不保存,直接迭代之后,self.words =map(lambda i: i.strip('\n'), f.readlines())

self.words 里边的数据会丢失,因此这个地方加了一个list()函数,将iterable到处保存。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值