第1 7題 Python敏感詞檢測

2021-07-28 22:39:05 字數 2319 閱讀 1163

題目來自:python 練習冊。題目1.7:敏感詞文字檔案 filtered_words.txt,裡面的內容為以下內容,當使用者輸入敏感詞語時,則列印出 freedom,否則列印出 human rights。

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() 方法用於移除字串頭尾指定的字元(預設為空格)。

strip()方法語法:

str.strip([chars]);

chars -- 移除字串頭尾指定的字元。

返回移除字串頭尾指定的字元生成的新字串。

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

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

print str.strip( '0' );

以上例項輸出結果如下:

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

很簡單,第乙個引數接收乙個函式名,第二個引數接收乙個可迭代物件。

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
#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到處儲存。

檢測敏感詞的 PHP 擴充套件

敏感詞過濾是我朝程式設計師必須具備的一種特殊技能,隨著敏感詞越來越多,是時候寫個擴充套件來快速的進行敏感詞檢測了 使用說明 1.安裝 libdatrie tar zxf libdatrie 0.2.4.tar.gz cd libdatrie 0.2.4 configure prefix usr lo...

python 敏感詞過濾2

敏感詞儲存在txt檔案中,當使用者輸入敏感詞語,則用 星號 替換,例如當使用者輸入 北京是個好城市 則變成 是個好城市 思路整理 1.獲取敏感詞檔案,讀取檔案,將檔案放入列表 2.獲取使用者輸入 3.檢查使用者輸入,是否有敏感詞語,4.若是輸入中有敏感詞語,將敏感詞用同等長度的 替換 5.若是輸入中...

Python 敏感詞過濾的實現

乙個簡單的實現 class filter filter messages from keywords very filter implementation f filter f.add y f.filter hello y baby hello baby def init self self.key...