通过reddit bot的单词列表在for循环中过滤字符串 [英] Filter strings in a for loop by list of words for reddit bot

查看:192
本文介绍了通过reddit bot的单词列表在for循环中过滤字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图写一个reddit机器人来查找标题中某些单词的文章。这是我到目前为止:

  top_posts = page.hot(限制= 20)
在top_posts中发布:
title = post.title
如果title.lower()在['word1','word2','word3']:
print(title)

$ b $ p








$ b $ p $ title.lower():
print(title)

那么它会打印标题中有 word1 的标题,但是当我把它放到列表中时不会。我想用一个列表来匹配同一个单词的不同拼写。我在这里做错了什么?

解决方案

你有错误地放置操作数的顺序,你做得不对。



使用 any 来检查列表中是否包含任何字词。



('word1','word2','word3']):
print(title)$ b中的wd中的title.lower()中的wd $ b

若要检查中是否包含所有 title ,请使用 all 来代替。


So I'm trying to write a reddit bot to find articles with certain words in the title. Here's what I have so far:

top_posts = page.hot(limit=20)
for post in top_posts:
    title = post.title
    if title.lower() in ['word1',  'word2', 'word3']:
        print(title)

If I replace the last 2 lines with...

    if 'word1' in title.lower():
        print(title)

then it'll print the titles that have word1 in them but when I put it into a list it won't. I want to use a list to match different spellings of the same word. What am I doing wrong here?

解决方案

You have the order of the operands wrongly placed and you're not doing it right.

Use any to check if any of words in the list is contained in the title:

if any(wd in title.lower() for wd in ['word1',  'word2', 'word3']):
    print(title)

To check if all of the words are contained in title, use all instead.

这篇关于通过reddit bot的单词列表在for循环中过滤字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆