Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
感詞過濾是隨著互聯(lián)網(wǎng)社區(qū)一起發(fā)展起來的一種阻止網(wǎng)絡(luò)犯罪和網(wǎng)絡(luò)暴力的技術(shù)手段,通過對可能存在犯罪或網(wǎng)絡(luò)暴力的關(guān)鍵詞進(jìn)行有針對性的篩查和屏蔽,能夠防患于未然,將后果嚴(yán)重的犯罪行為扼殺于萌芽之中。
隨著各種社交論壇的日益火爆,敏感詞過濾逐漸成為了非常重要的功能。那么在 Serverless 架構(gòu)下,利用 Python 語言,敏感詞過濾又有那些新的實(shí)現(xiàn)呢?我們能否用最簡單的方法實(shí)現(xiàn)一個(gè)敏感詞過濾的 API 呢?
如果說敏感詞過濾,其實(shí)不如說是文本的替換,以Python為例,說到詞匯替換,不得不想到replace,我們可以準(zhǔn)備一個(gè)敏感詞庫,然后通過replace進(jìn)行敏感詞替換:
def worldFilter(keywords, text):
for eve in keywords:
text=text.replace(eve, "***")
return text
keywords=("關(guān)鍵詞1", "關(guān)鍵詞2", "關(guān)鍵詞3")
content="這是一個(gè)關(guān)鍵詞替換的例子,這里涉及到了關(guān)鍵詞1還有關(guān)鍵詞2,最后還會(huì)有關(guān)鍵詞3。"
print(worldFilter(keywords, content))
但是動(dòng)動(dòng)腦大家就會(huì)發(fā)現(xiàn),這種做法在文本和敏感詞庫非常龐大的前提下,會(huì)有很嚴(yán)重的性能問題。例如我將代碼進(jìn)行修改,進(jìn)行基本的性能測試:
import time
def worldFilter(keywords, text):
for eve in keywords:
text=text.replace(eve, "***")
return text
keywords=[ "關(guān)鍵詞" + str(i) for i in range(0,10000)]
content="這是一個(gè)關(guān)鍵詞替換的例子,這里涉及到了關(guān)鍵詞1還有關(guān)鍵詞2,最后還會(huì)有關(guān)鍵詞3。" * 1000
startTime=time.time()
worldFilter(keywords, content)
print(time.time()-startTime)
此時(shí)的輸出結(jié)果是:0.12426114082336426,可以看到性能非常差。
與其用replace,還不如通過正則表達(dá)re.sub來的更加快速。
import time
import re
def worldFilter(keywords, text):
return re.sub("|".join(keywords), "***", text)
keywords=[ "關(guān)鍵詞" + str(i) for i in range(0,10000)]
content="這是一個(gè)關(guān)鍵詞替換的例子,這里涉及到了關(guān)鍵詞1還有關(guān)鍵詞2,最后還會(huì)有關(guān)鍵詞3。" * 1000
startTime=time.time()
worldFilter(keywords, content)
print(time.time()-startTime)
我們同樣增加性能測試,按照上面的方法進(jìn)行改造測試,輸出結(jié)果是0.24773502349853516。通過這樣的例子,我們可以發(fā)現(xiàn),其性能磣韓劇并不大,但是實(shí)際上隨著文本量增加,正則表達(dá)這種做法在性能層面會(huì)變高很多。
這種方法相對來說效率會(huì)更高一些。例如,我們認(rèn)為壞人,壞孩子,壞蛋是敏感詞,則他們的樹關(guān)系可以表達(dá):
用DFA字典來表示:
{
'壞': {
'蛋': {
'\x00': 0
},
'人': {
'\x00': 0
},
'孩': {
'子': {
'\x00': 0
}
}
}
}
使用這種樹表示問題最大的好處就是可以降低檢索次數(shù),提高檢索效率,基本代碼實(shí)現(xiàn):
import time
class DFAFilter(object):
def __init__(self):
self.keyword_chains={} # 關(guān)鍵詞鏈表
self.delimit='\x00' # 限定
def parse(self, path):
with open(path, encoding='utf-8') as f:
for keyword in f:
chars=str(keyword).strip().lower() # 關(guān)鍵詞英文變?yōu)樾?
if not chars: # 如果關(guān)鍵詞為空直接返回
return
level=self.keyword_chains
for i in range(len(chars)):
if chars[i] in level:
level=level[chars[i]]
else:
if not isinstance(level, dict):
break
for j in range(i, len(chars)):
level[chars[j]]={}
last_level, last_char=level, chars[j]
level=level[chars[j]]
last_level[last_char]={self.delimit: 0}
break
if i==len(chars) - 1:
level[self.delimit]=0
def filter(self, message, repl="*"):
message=message.lower()
ret=[]
start=0
while start < len(message):
level=self.keyword_chains
step_ins=0
for char in message[start:]:
if char in level:
step_ins +=1
if self.delimit not in level[char]:
level=level[char]
else:
ret.append(repl * step_ins)
start +=step_ins - 1
break
else:
ret.append(message[start])
break
else:
ret.append(message[start])
start +=1
return ''.join(ret)
gfw=DFAFilter()
gfw.parse( "./sensitive_words")
content="這是一個(gè)關(guān)鍵詞替換的例子,這里涉及到了關(guān)鍵詞1還有關(guān)鍵詞2,最后還會(huì)有關(guān)鍵詞3。" * 1000
startTime=time.time()
result=gfw.filter(content)
print(time.time()-startTime)
這里我們的字典庫是:
with open("./sensitive_words", 'w') as f:
f.write("\n".join( [ "關(guān)鍵詞" + str(i) for i in range(0,10000)]))
執(zhí)行結(jié)果:
0.06450581550598145
可以看到性能進(jìn)一步提升。
接下來,我們來看一下 AC自動(dòng)機(jī)過濾敏感詞算法:
AC自動(dòng)機(jī):一個(gè)常見的例子就是給出n個(gè)單詞,再給出一段包含m個(gè)字符的文章,讓你找出有多少個(gè)單詞在文章里出現(xiàn)過。
簡單地講,AC自動(dòng)機(jī)就是字典樹+kmp算法+失配指針
代碼實(shí)現(xiàn):
import time
class Node(object):
def __init__(self):
self.next={}
self.fail=None
self.isWord=False
self.word=""
class AcAutomation(object):
def __init__(self):
self.root=Node()
# 查找敏感詞函數(shù)
def search(self, content):
p=self.root
result=[]
currentposition=0
while currentposition < len(content):
word=content[currentposition]
while word in p.next==False and p !=self.root:
p=p.fail
if word in p.next:
p=p.next[word]
else:
p=self.root
if p.isWord:
result.append(p.word)
p=self.root
currentposition +=1
return result
# 加載敏感詞庫函數(shù)
def parse(self, path):
with open(path, encoding='utf-8') as f:
for keyword in f:
temp_root=self.root
for char in str(keyword).strip():
if char not in temp_root.next:
temp_root.next[char]=Node()
temp_root=temp_root.next[char]
temp_root.isWord=True
temp_root.word=str(keyword).strip()
# 敏感詞替換函數(shù)
def wordsFilter(self, text):
"""
:param ah: AC自動(dòng)機(jī)
:param text: 文本
:return: 過濾敏感詞之后的文本
"""
result=list(set(self.search(text)))
for x in result:
m=text.replace(x, '*' * len(x))
text=m
return text
acAutomation=AcAutomation()
acAutomation.parse('./sensitive_words')
startTime=time.time()
print(acAutomation.wordsFilter("這是一個(gè)關(guān)鍵詞替換的例子,這里涉及到了關(guān)鍵詞1還有關(guān)鍵詞2,最后還會(huì)有關(guān)鍵詞3。"*1000))
print(time.time()-startTime)
詞庫同樣是:
with open("./sensitive_words", 'w') as f:
f.write("\n".join( [ "關(guān)鍵詞" + str(i) for i in range(0,10000)]))
使用上面的方法,測試結(jié)果為0.017391204833984375。
可以看到這個(gè)所有算法中,在上述的基本算法中DFA過濾敏感詞性能最高,但是實(shí)際上,對于后兩者算法,并沒有誰一定更好,可能某些時(shí)候,AC自動(dòng)機(jī)過濾敏感詞算法會(huì)得到更高的性能,所以在生產(chǎn)生活中,推薦時(shí)候用兩者,可以根據(jù)自己的具體業(yè)務(wù)需要來做。
將代碼部署到Serverless架構(gòu)上,可以選擇API網(wǎng)關(guān)與函數(shù)計(jì)算進(jìn)行結(jié)合,以AC自動(dòng)機(jī)過濾敏感詞算法為例:我們只需要增加是幾行代碼就好,完整代碼如下:
# -*- coding:utf-8 -*-
import json, uuid
class Node(object):
def __init__(self):
self.next={}
self.fail=None
self.isWord=False
self.word=""
class AcAutomation(object):
def __init__(self):
self.root=Node()
# 查找敏感詞函數(shù)
def search(self, content):
p=self.root
result=[]
currentposition=0
while currentposition < len(content):
word=content[currentposition]
while word in p.next==False and p !=self.root:
p=p.fail
if word in p.next:
p=p.next[word]
else:
p=self.root
if p.isWord:
result.append(p.word)
p=self.root
currentposition +=1
return result
# 加載敏感詞庫函數(shù)
def parse(self, path):
with open(path, encoding='utf-8') as f:
for keyword in f:
temp_root=self.root
for char in str(keyword).strip():
if char not in temp_root.next:
temp_root.next[char]=Node()
temp_root=temp_root.next[char]
temp_root.isWord=True
temp_root.word=str(keyword).strip()
# 敏感詞替換函數(shù)
def wordsFilter(self, text):
"""
:param ah: AC自動(dòng)機(jī)
:param text: 文本
:return: 過濾敏感詞之后的文本
"""
result=list(set(self.search(text)))
for x in result:
m=text.replace(x, '*' * len(x))
text=m
return text
def response(msg, error=False):
return_data={
"uuid": str(uuid.uuid1()),
"error": error,
"message": msg
}
print(return_data)
return return_data
acAutomation=AcAutomation()
path='./sensitive_words'
acAutomation.parse(path)
def main_handler(event, context):
try:
sourceContent=json.loads(event["body"])["content"]
return response({
"sourceContent": sourceContent,
"filtedContent": acAutomation.wordsFilter(sourceContent)
})
except Exception as e:
return response(str(e), True)
最后,為了方便本地測試,我們可以增加:
def test():
event={
"requestContext": {
"serviceId": "service-f94sy04v",
"path": "/test/{path}",
"httpMethod": "POST",
"requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
"identity": {
"secretId": "abdcdxxxxxxxsdfs"
},
"sourceIp": "14.17.22.34",
"stage": "release"
},
"headers": {
"Accept-Language": "en-US,en,cn",
"Accept": "text/html,application/xml,application/json",
"Host": "service-3ei3tii4-251000691.ap-guangzhou.apigateway.myqloud.com",
"User-Agent": "User Agent String"
},
"body": "{\"content\":\"這是一個(gè)測試的文本,我也就呵呵了\"}",
"pathParameters": {
"path": "value"
},
"queryStringParameters": {
"foo": "bar"
},
"headerParameters": {
"Refer": "10.0.2.14"
},
"stageVariables": {
"stage": "release"
},
"path": "/test/value",
"queryString": {
"foo": "bar",
"bob": "alice"
},
"httpMethod": "POST"
}
print(main_handler(event, None))
if __name__=="__main__":
test()
完成之后,我們就可以測試運(yùn)行一下,例如我的字典是:
呵呵
測試
執(zhí)行之后結(jié)果:
{'uuid': '9961ae2a-5cfc-11ea-a7c2-acde48001122', 'error': False, 'message': {'sourceContent': '這是一個(gè)測試的文本,我也就呵呵了', 'filtedContent': '這是一個(gè)**的文本,我也就**了'}}
接下來,我們將代碼部署到云端,新建serverless.yaml:
sensitive_word_filtering:
component: "@serverless/tencent-scf"
inputs:
name: sensitive_word_filtering
codeUri: ./
exclude:
- .gitignore
- .git/**
- .serverless
- .env
handler: index.main_handler
runtime: Python3.6
region: ap-beijing
description: 敏感詞過濾
memorySize: 64
timeout: 2
events:
- apigw:
name: serverless
parameters:
environment: release
endpoints:
- path: /sensitive_word_filtering
description: 敏感詞過濾
method: POST
enableCORS: true
param:
- name: content
position: BODY
required: 'FALSE'
type: string
desc: 待過濾的句子
然后通過sls --debug進(jìn)行部署,部署結(jié)果:
最后,通過PostMan進(jìn)行測試:
敏感詞過濾是目前非常常見的需求/技術(shù),通過敏感詞過濾,我們可以在一定程度上降低惡意言語或者違規(guī)言論的出現(xiàn),在上述實(shí)踐過程,有以下兩點(diǎn)內(nèi)容:
Serverless Framework 試用計(jì)劃
我們誠邀您來體驗(yàn)最便捷的 Serverless 開發(fā)和部署方式。在試用期內(nèi),相關(guān)聯(lián)的產(chǎn)品及服務(wù)均提供免費(fèi)資源和專業(yè)的技術(shù)支持,幫助您的業(yè)務(wù)快速、便捷地實(shí)現(xiàn) Serverless!
Serverless Framework 是構(gòu)建和運(yùn)維 Serverless 應(yīng)用的框架。簡單三步,即可通過 Serverless Framework 快速實(shí)現(xiàn)服務(wù)部署。
1. 安裝 Serverless
macOS/Linux 系統(tǒng):推薦使用二進(jìn)制安裝
$ curl -o- -L https://slss.io/install | bash
Windows 系統(tǒng):可通過 npm 安裝
$ npm install -g serverless
2. 創(chuàng)建云上應(yīng)用
在空文件夾下輸入 `serverless` 命令
$ serverless
訪問命令行中輸出的鏈接,即可訪問成功部署后的應(yīng)用。
3. 查看部署信息
進(jìn)入到部署成功的文件夾,運(yùn)行如下命令,查看部署狀態(tài)和資源信息:
$ sls info
用戶在 HTML 表單中填寫并提交數(shù)據(jù)時(shí),可以使用 PHP 來接收并處理這些數(shù)據(jù)。要實(shí)現(xiàn)這一點(diǎn),需要?jiǎng)?chuàng)建一個(gè) PHP 腳本來處理提交的數(shù)據(jù),然后將 HTML 表單的 "action" 屬性設(shè)置為該腳本的文件路徑。表單提交的數(shù)據(jù)需要進(jìn)行驗(yàn)證和過濾,以確保數(shù)據(jù)的完整性和安全性。可以使用條件語句、正則表達(dá)式、過濾器函數(shù)等方法來驗(yàn)證和過濾數(shù)據(jù),并使用 htmlspecialchars() 函數(shù)轉(zhuǎn)義 HTML 標(biāo)記,以防止 XSS 攻擊。
以下是一個(gè)簡單的示例:
HTML 表單代碼:
<form action="submit.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<button type="submit">Submit</button>
</form>
PHP 代碼(submit.php):
<?php
// 獲取表單提交的數(shù)據(jù)
$name=$_POST['name'];
$email=$_POST['email'];
// 在這里進(jìn)行處理,例如將數(shù)據(jù)存儲(chǔ)到數(shù)據(jù)庫中
// ...
// 返回一個(gè)響應(yīng),告訴用戶數(shù)據(jù)已經(jīng)被成功提交
echo "Thank you for submitting the form, $name!";
?>
在上面的示例中,表單的 "action" 屬性設(shè)置為 "submit.php",這意味著提交表單時(shí),數(shù)據(jù)將被發(fā)送到 submit.php 文件中的 PHP 代碼中進(jìn)行處理。PHP 代碼使用 $_POST 數(shù)組來獲取表單提交的數(shù)據(jù),然后進(jìn)行處理,例如將數(shù)據(jù)存儲(chǔ)到數(shù)據(jù)庫中。最后,PHP 代碼返回一個(gè)響應(yīng),告訴用戶數(shù)據(jù)已經(jīng)被成功提交。在處理表單數(shù)據(jù)時(shí),一定要對用戶輸入進(jìn)行驗(yàn)證和過濾,以防止安全漏洞。
需要對表單提交的數(shù)據(jù)進(jìn)行驗(yàn)證和過濾,以確保數(shù)據(jù)的完整性和安全性。以下是一些常見的方法:
1、驗(yàn)證表單字段:在 PHP 代碼中使用條件語句和正則表達(dá)式等方法來驗(yàn)證表單字段的有效性,例如驗(yàn)證電子郵件地址的格式是否正確。
$email=$_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// 如果郵件地址格式不正確,則顯示錯(cuò)誤消息
echo "Invalid email address";
}
2、過濾輸入數(shù)據(jù):使用 PHP 中的過濾器函數(shù)來過濾表單輸入數(shù)據(jù),以防止 XSS 攻擊和 SQL 注入等安全漏洞。
$name=$_POST['name'];
$name=filter_var($name, FILTER_SANITIZE_STRING); // 過濾特殊字符和標(biāo)簽
3、防止跨站腳本攻擊(XSS):在 PHP 代碼中使用 htmlspecialchars() 函數(shù)來轉(zhuǎn)義 HTML 標(biāo)記,防止惡意腳本注入到頁面中。
$name=$_POST['name'];
$name=htmlspecialchars($name, ENT_QUOTES, 'UTF-8'); // 轉(zhuǎn)義 HTML 標(biāo)記
4、防止 SQL 注入攻擊:在 PHP 代碼中使用參數(shù)化查詢或準(zhǔn)備語句來執(zhí)行數(shù)據(jù)庫操作,以防止惡意 SQL 語句注入到數(shù)據(jù)庫中。
$stmt=$pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->execute();
通過這些方法,可以確保表單提交的數(shù)據(jù)是安全和有效的,并且能夠正常地處理和存儲(chǔ)到數(shù)據(jù)庫中。
一些字符在 HTML 中擁有特殊的含義,比如小于號(hào) (<) 用于定義 HTML 標(biāo)簽的開始,所以有時(shí)候直接在頁面中書寫的話,會(huì)產(chǎn)生意想不到的結(jié)果。如果我們希望瀏覽器正確地顯示這些字符,我們必須在 HTML 源碼中插入字符實(shí)體。
字符實(shí)體有三部分:一個(gè)和號(hào) (&),一個(gè)實(shí)體名稱或者 # 和一個(gè)實(shí)體編號(hào),以及一個(gè)分號(hào) (;)。
要在 HTML 文檔中顯示小于號(hào),我們需要這樣寫:< 或者 <
使用實(shí)體名稱而不是實(shí)體編號(hào)的好處在于,名稱相對來說更容易記憶。而這么做的壞處是,并不是所有的瀏覽器都支持最新的實(shí)體名稱,然而幾乎所有的瀏覽器對實(shí)體編號(hào)的支持都很好。
注意:實(shí)體對大小寫敏感。
空格
空格是 HTML 中最普通的字符實(shí)體。
通常情況下,HTML 會(huì)裁掉文檔中的空格。假如你在文檔中連續(xù)輸入 10 個(gè)空格,那么 HTML 會(huì)去掉其中的9個(gè)而只顯示1個(gè)。如果使用 就可以在文檔中增加空格。
以下就羅列下html頁面能使用到的字符實(shí)體
顯示結(jié)果 | 描述 | 實(shí)體名稱 | 實(shí)體編號(hào) |
空格 |
|
| |
< | 小于號(hào) | < | < |
> | 大于號(hào) | > | > |
& | 和號(hào) | & | & |
" | 引號(hào) | " | " |
' | 撇號(hào) | ' (IE不支持) | ' |
顯示結(jié)果 | 描述 | 實(shí)體名稱 | 實(shí)體編號(hào) |
¢ | 分 | ¢ | ¢ |
£ | 鎊 | £ | £ |
¥ | 日圓 | ¥ | ¥ |
§ | 節(jié) | § | § |
? | 版權(quán) | © | © |
? | 注冊商標(biāo) | ® | ® |
× | 乘號(hào) | × | × |
÷ | 除號(hào) | ÷ | ÷ |
*請認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。