2 回答

TA贡献2080条经验 获得超4个赞
不是现在,但您将能够在 Python 3.8 中通过赋值表达式:
elif any((caught := z) in tweet.text.lower().split() for z in config.banned_name_keywords):
print("Avoided tweet with word: " + caught)
如果你想捕获所有可能出现的禁用词,你不能使用any,因为它的目的是在你找到一个匹配项时立即停止。为此,您只想计算交集(您今天也可以这样做):
banned = set(config.banned_name_keywords)
...
else:
caught = banned.intersection(tweet.text.lower().split())
if caught:
print("Avoided tweet with banned words: " + caught)
(它本身也可以使用赋值表达式来缩短:
elif (caught := banned.intersection(tweet.text.lower().split())):
print("Avoided tweet with banned words: " + caught)
)

TA贡献1797条经验 获得超6个赞
更改此行
if tweet.user.screen_name.lower() in config.banned_users or any(x in tweet.user.name.lower() for x in config.banned_name_keywords):
到
try:
# matched_banned_keyword below is the `SPECIFIC` word that matched
matched_banned_keyword = config.banned_name_keywords[config.banned_name_keywords.index(tweet.user.name.lower())]
except:
matched_banned_keyword = None
if tweet.user.screen_name.lower() in config.banned_users or matched_banned_keyword:
print("Avoided user with ID: " + tweet.user.screen_name + " & Name: " + tweet.user.name)
L.index(x)x函数返回列表中的索引,如果列表中不存在,则L引发异常。您可以捕获在您的情况下不存在时会发生的异常xLuser.screen_name.lower()config.banned_name_keywords
添加回答
举报