題目來自:Python 練習(xí)冊。題目1.7:敏感詞文本文件 filtered_words.txt,里面的內(nèi)容為以下內(nèi)容,當用戶輸入敏感詞語時,則打印出 Freedom,否則打印出 Human Rights。
查看更多于本人博客:iii.run
Python find()方法
描述
Python find() 方法檢測字符串中是否包含子字符串 str ,如果指定 beg(開始) 和 end(結(jié)束) 范圍,則檢查是否包含在指定范圍內(nèi),如果包含子字符串返回開始的索引值,否則返回-1。
語法
find()方法語法:
str.find(str, beg=0, end=len(string))
參數(shù)
str -- 指定檢索的字符串
beg -- 開始索引,默認為0。
end -- 結(jié)束索引,默認為字符串的長度。
返回值
如果包含子字符串返回開始的索引值,否則返回-1。
實例
以下實例展示了find()方法的實例:
info = 'abca'
print info.find('a')##從下標0開始,查找在字符串里第一個出現(xiàn)的子串,返回結(jié)果:0
info = 'abca'
print info.find('a',1)##從下標1開始,查找在字符串里第一個出現(xiàn)的子串:返回結(jié)果3
info = 'abca'
print info.find('333')##返回-1,查找不到返回-1
Python strip()方法
描述
Python strip() 方法用于移除字符串頭尾指定的字符(默認為空格)。
語法
strip()方法語法:
str.strip([chars]);
參數(shù)
chars -- 移除字符串頭尾指定的字符。
返回值
返回移除字符串頭尾指定的字符生成的新字符串。
實例
以下實例展示了strip()函數(shù)的使用方法:
str = "0000000this is string example....wow!!!0000000";
print str.strip( '0' );
以上實例輸出結(jié)果如下:
this is string example....wow!!!
Python map()方法
描述
很簡單,第一個參數(shù)接收一個函數(shù)名,第二個參數(shù)接收一個可迭代對象。
語法
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]
參考代碼
filtered_words.txt
將文件下載到D盤內(nèi)即可
#coding: utf-8
import cmd
# 存放敏感詞文件的路徑
filtered_words_filepath = 'd:/filtered_words.txt'
class CLI(cmd.Cmd):
def __init__(self): #初始基礎(chǔ)類方法
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()
其實這個地方出現(xiàn)過一個錯誤,map()形成的iterable是一次性的。
也就是如果不保存,直接迭代之后,self.words =map(lambda i: i.strip('\n'), f.readlines())
self.words 里邊的數(shù)據(jù)會丟失,因此這個地方加了一個list()函數(shù),將iterable到處保存。