如果消息中有坏词:类型错误:'in'需要字符串作为左操作数,而不是列表
所以我有一个 BadWords.txt 文件,我已将其嵌入到 BW_Filter.py 中,
这里是 BW_Filter.py 代码:
with open('BadWords.txt') as f:
words = f.read()
BadWords = words.split()
def on_message():
msg = input("Type: ")
if BadWords in msg:
print("Dont use that word!")
elif BadWords not in msg:
print("Message send!")
on_message()
如果我现在从 BadWord.txt 文件中输入一个带有 BadWord 的句子,或者只是单个 BadWord 而没有其他内容话,比它给我一个这样的错误:
if BadWords in msg: TypeError: 'in
(在我关于 stackoverflow 的其他问题中(没有人正确回答或理解)它可以工作,但只是包含 BadWords 的 BadWords.txt 文件的第一个单词)
然后我改变了一些事情,现在代码看起来像这样:
with open('BadWords.txt') as f:
words = f.read()
BadWords = words.split()
def on_message():
msg = input("Type: ")
if BadWords.__contains__(msg):
print("Dont use that word!")
else:
print("Message send!")
on_message()
在这段代码中,问题是我无法用 BadWords 写句子,但是如果我输入一个 BadWord 单词而没有其他单词,它就可以工作。
我以前曾问过类似的问题,但现在我改变了一些东西,然后再次询问。
So i have an BadWords.txt file, that i have embedded in the BW_Filter.py
here is the BW_Filter.py code:
with open('BadWords.txt') as f:
words = f.read()
BadWords = words.split()
def on_message():
msg = input("Type: ")
if BadWords in msg:
print("Dont use that word!")
elif BadWords not in msg:
print("Message send!")
on_message()
if i now type a sentence with a BadWord from the BadWord.txt file, or just the BadWord in single without other words, than it gives me an error like this:
if BadWords in msg: TypeError: 'in <string>' requires string as left operand, not list
(In my other question on stackoverflow(that no one had answer correctly, or understandful)there it works, but just with the first word of the BadWords.txt file that contains the BadWords)
then i changed some things and now the code looks like so:
with open('BadWords.txt') as f:
words = f.read()
BadWords = words.split()
def on_message():
msg = input("Type: ")
if BadWords.__contains__(msg):
print("Dont use that word!")
else:
print("Message send!")
on_message()
in this code is the problem that i cannot write sentences with the BadWords, but if i type a BadWord single without other words it works.
I have asked a question before with a similar problem, but now i changed some things, and ask again.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
而不是:
do:
您不允许执行
list in str
(如错误消息所示),但使用any
可以让您轻松循环遍历 str 中的每个项目列出并执行单独的str in str
检查,如果这些检查中的任何一个返回True
,则结果为True
。Instead of:
do:
You aren't allowed to do
list in str
(as the error message indicates), but usingany
allows you to easily loop through each item in the list and do individualstr in str
checks, with aTrue
result ifany
of those checks returnsTrue
.