2 回答

TA貢獻2080條經驗 獲得超4個贊
不是現(xiàn)在,但您將能夠在 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)
如果你想捕獲所有可能出現(xiàn)的禁用詞,你不能使用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引發(fā)異常。您可以捕獲在您的情況下不存在時會發(fā)生的異常xLuser.screen_name.lower()config.banned_name_keywords
添加回答
舉報