我可以返回在任何迭代中找到的值吗?

我正在自学python,并且正在对其他人编写的机器人进行一些更改。


我正在尝试为 NSFW 或不适合儿童的单词添加过滤器。我已将这些词添加到名为 config.banned_name_keywords 的列表中。


我最初通过返回整个推文使其正常工作,但我试图返回找到的特定单词,以便我可以排除故障并编辑列表。


我可以使用 tweet.text 返回整个推文,但这会影响输出并阻塞屏幕。


我也试过 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


达令说
浏览 125回答 2
2回答

犯罪嫌疑人X

不是现在,但您将能够在 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))

互换的青春

更改此行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 = Noneif 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python