You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行Python ahocorasick敏感词屏蔽代码报wordlist未定义如何解决

问题根因

你的错误完全是变量定义顺序和代码执行逻辑不匹配导致的:

  • Python代码按从上到下的顺序执行,你在调用build_actree(wordlist=wordlist)这一行时,wordlist还没有被定义,它的定义被你写到了后续的for循环内部,所以直接触发未定义报错。
  • 除了wordlist之外,sent变量也存在同样的问题,你在sent_cp = sent这一行赋值时sent还没有定义,修复完wordlist的问题后会继续触发sent的未定义报错。
  • 额外的逻辑问题:你把待检测的句子、敏感词列表的定义都放在了遍历匹配的for循环内部,就算解决了变量定义问题,匹配逻辑也完全无法正常运行。

修正后的代码

import ahocorasick

def build_actree(wordlist):
    actree = ahocorasick.Automaton()
    for index, word in enumerate(wordlist):
        actree.add_word(word, (index, word))
    actree.make_automaton()
    return actree

if __name__ == '__main__':
    # 先定义敏感词列表和待检测句子
    wordlist =['我草']
    sent = '我草你妈'
    # 再构建AC树、初始化拷贝变量
    actree = build_actree(wordlist=wordlist)
    sent_cp = sent
    # 最后执行匹配替换
    for i in actree.iter(sent):
        sent_cp = sent_cp.replace(i[1][1], "**")
        print("屏蔽词:",i[1][1])
    print("屏蔽结果:",sent_cp)

运行输出

屏蔽词: 我草
屏蔽结果: **你妈

内容的提问来源于stack exchange,提问作者高汤娃娃菜

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:51:00