我目前正在为Twitch.tv开发一个IRC机器人,我想知道如何实现一个禁止使用的单词列表?这是我到目前为止所拥有的东西,由于我对python的知识有限,我很困惑。到目前为止,一切都很好,除了检查信息中是否有被禁止的单词。这是所讨论的代码位:
if bannedWords.split in message:
sendMessage(s, "/ban " + user)
break
我想查一下名单,看看邮件里有没有名单上的内容?
bannedWords = ["badword1", "badword1"]
但我不确定。。
import string
from Read import getUser, getMessage
from Socket import openSocket, sendMessage
from Initialize import joinRoom
s = openSocket()
joinRoom(s)
readbuffer = ""
bannedWords = ["badword1", "badword1"]
while True:
readbuffer = readbuffer + s.recv(1024)
temp = string.split(readbuffer, "\n")
readbuffer = temp.pop()
for line in temp:
print(line)
if "PING" in line:
s.send(line.replace("PING", "PONG"))
break
user = getUser(line)
message = getMessage(line)
print user + " typed :" + message
if bannedWords.split in message:
sendMessage(s, "/ban " + user)
break
提前谢谢!!
最佳答案
如果需要完全匹配,请使用一组单词,对字符串调用lower并检查该组不匹配的单词是否不相交:
banned_set = {"badword1", "badword2"}
if banned_set.isdisjoint(message.lower().split())
# no bad words
如果
"foo"
是被禁止的并且"foobar"
是完全有效的,那么使用in/__contains__
将错误地过滤单词,因此您需要仔细决定要走的路。如果
banned_set.isdisjoint(message.lower().split())
评估为真,则可以安全地继续:In [3]: banned_set = {"badword1", "badword2"}
In [4]: banned_set.isdisjoint("foo bar".split())
Out[4]: True
In [5]: banned_set.isdisjoint("foo bar badword1".split())
Out[5]: False
关于python - 抽搐的原始Python IRC聊天机器人,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36361679/