我正在自学python,并对其他人编写的机器人进行了一些更改。
我正在尝试为NSFW或不适合孩子的单词添加过滤器。我已将这些单词添加到名为config.banned_name_keywords的列表中。
我本来可以通过返回整个tweet来使其正常工作,但我正尝试返回找到的特殊单词,以便对列表进行故障排除和编辑。
我可以使用tweet.text返回整个tweet,但是这将使输出消失并阻塞屏幕。
我也尝试过print(x),但是我不知道在哪里定义。它返回的是首先找到该推文的单词。
for tweet in searched_tweets:
if any(rtwords in tweet.text.lower().split() for rtwords in config.retweet_tags):
# The script only cares about contests that require retweeting. It would be very weird to not have to
# retweet anything; that usually means that there's a link you gotta open and then fill up a form.
# This clause checks if the text contains any retweet_tags
if tweet.retweeted_status is not None:
# In case it is a retweet, we switch to the original one
if any(y in tweet.retweeted_status.text.lower().split() for y in config.retweet_tags):
tweet = tweet.retweeted_status
else:
continue
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):
# If it's the original one, we check if the author is banned
print("Avoided user with ID: " + tweet.user.screen_name + " & Name: " + tweet.user.name)
continue
elif any(z in tweet.text.lower().split() for z in config.banned_name_keywords):
# If the author isn't banned, we check for words we don't want
print("Avoided tweet with words:" + z)
continue
答案 0 :(得分:0)
不是现在,但是您将能够通过assignment expressions在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)
)
答案 1 :(得分:0)
更改此行
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
的索引,如果列表x
中不存在L
,则会引发异常。您可以捕获在user.screen_name.lower()
中不存在config.banned_name_keywords