屏蔽禁用語&KMP

來源:互聯網
上載者:User

在互連網上,由於一些政策法規,需要對一些文章或者聊天記錄進行關鍵字屏蔽,本文使用KMP模式比對演算法,將目標串S中的禁用語全部替換成*。

實際應用中需要一個屏蔽詞庫,需將每個屏蔽詞條作為模式串T,分別過濾一次S串。

考慮到屏蔽詞庫中有相同首碼的屏蔽詞,比如:“朱令”和“朱令案”,所以可以預先將屏蔽詞庫中的屏蔽詞按照長度做由大到小的排序。先過濾長詞,再過濾短詞即可。

int getNext(char* s, int next[]) {    next[0] = -1;    int i = -1;    int j = 0;    while (j < strlen(s)) {        if (i == -1 || s[i] == s[j]) {            i++;            j++;            next[j] = i;        } else {            i = next[i];        }    }    return 0;}int kmp(char* str, char* t, int next[]) {    int j = 0;    int i = 0;    while (str[i] != '\0' && t[j] != '\0' && strlen(str) - i >= strlen(t) - j) {        if (str[i] == t[j]) {            i++;            j++;        } else {            j = next[j];            if (j == -1) {                i++;                j++;            }        }        if (t[j] == '\0') {            i = i - j;            return i;        }    }    return -1;}int fillStar(char* p, int len) {    int i = 0;    while (i < len) {        p[i] = '*';        i++;    }    return 0;}int filter(char* s, char* t) {    int len = strlen(t);    int next[LEN];    getNext(t, next);    char* p = s;    while (p != '\0') {        int loc = kmp(p, t, next);        if (loc >= 0) {            fillStar(p + loc, len);            p = (p + loc + len);        } else {            return 0;        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.