gpt4 book ai didi

python - 搜索字符串中的禁用词

转载 作者:行者123 更新时间:2023-12-01 04:54:57 25 4
gpt4 key购买 nike

我想检测字符串中的粗俗单词。我有一个存储在 .txt 文件中的不雅词语数据库。我将此文件放入我的 .py 文件中。

坏词示例:

words = "word, something, dog, cat ...."

输入数据字符串例如:

input = "xxxxdogxxx" or "dogxxxx" or "xxxdog" or "dog" "ok_word" # xxx == any word

我想要,当输入包含单词中的单词时返回为False

def check(input):
word = "something, something, ..."
x = ???? # I do not know how to do it, probably using regular expressions: re.match?
if x:
return False
else:
return True

最佳答案

实际上您不需要正则表达式。您可以使用 all 和一个generator expression :

def check(input):
return all(x not in input for x in bad_words)

要将单词字符串放入列表中,请使用 str.split :

>>> words = "word, something, dog, cat"
>>> words.split(', ')
['word', 'something', 'dog', 'cat']
>>>

您可能还想调用 set()列在列表中以缩短查找时间。套装有O(1) (恒定)复杂性为 innot in运算符,而列表有 O(n) (线性)。因此,在集合中查找内容比使用列表查找内容更快。

关于python - 搜索字符串中的禁用词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27650461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com