缓存匹配过滤器电话

2024-05-26 16:27:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我找了又找,但没有找到一个与我要找的主题/答案相匹配的主题/答案,所以这里。。在

我想实现一个(bad/profantity)单词过滤器,用通配符匹配字符串中单词列表中的任何单词,并返回匹配结果(如果找到)。在

这并不像“iswordinstring”那么简单,因为有些单词本身可能很顽皮,但在字符串的开头、中间和/或结尾都是可以接受的。e、 g“斯肯索普”!在

我担心的是(据我所知很少),在相对较长的字符串(最多2048个字符)上会有大量重复/迭代,而且每次都会调用模式列表—有没有办法缓存其中的任何一个?在

在聊天应用程序中,这个函数可以被频繁调用,并且有300多个单词的坏单词列表,所以效率是关键。在

这是我目前所拥有的,有不同匹配的示例,它的工作非常完美,但是作为一个Python新手,我不知道这是否有效,所以我希望专家能提供一些见解。在

def badWordMatch(string):
    bad_words = ["poo", "wee", "barsteward*", "?orrible"]
    data = string.split()
    for each in bad_words:
        l = fnmatch.filter(data, each)
        if l:
            return each.replace("?","").replace("*","")
    return None

string_input = "Please do not wee in the swimming pool you 'orrible naughty barstewards!" # Matched: "wee"
#string_input = "Please do not dive in the swimming pool you 'orrible naughty barstewards!" # Matched: "barsteward"
#string_input = "Please do not dive in the swimming pool you 'orrible naughty kids!" # Matched: "orrible"
#string_input = "Please do not dive in the swimming pool you horrible naughty kids!" # Matched: "orrible"
#string_input = "Please do not dive in the swimming pool you naughty kids!" # No match!

isbadword = badWordMatch(string_input)

if isbadword is not None:
    print("Matched: %s" % (isbadword))
else:
    print("No match, string is clean!")

更新:正则表达式版本:

^{pr2}$

结果:

匹配!便便 匹配!wee公司 匹配!好可怕 匹配!酒吧服务员!在


Tags: theinyouinputstringnot单词do
1条回答
网友
1楼 · 发布于 2024-05-26 16:27:58

在python3.2+中,fnmatch.filterhas a LRU cache decorator,这意味着缓存了最近的256个调用。{>^{} uses ^{} internally所以您的模式在内部被转换为regex and are hence cached automatically。在

最好还是从坏词列表中构建一个正则表达式,因为from this answer一个(显式编译)正则表达式比示例中几百个(隐式编译)正则表达式快得多。在

相关问题 更多 >

    热门问题