简体   繁体   English

如果字符串包含“ foo”,则执行此操作

[英]Python if string contains “foo” do this

I have a twitter bot that responds to tweets containing certain strings from array t . 我有一个Twitter机器人,它响应包含来自数组t某些字符串的推文。 I'm trying to write a conditional statement that restricts it from responding to tweets containing strings from another array, a . 我正在尝试编写条件语句,以限制其响应包含来自另一个数组a字符串的推文。 In theory it should work but it doesn't. 从理论上讲,它应该工作,但是没有。 The bot disregards the if/else statement. 机器人会忽略if / else语句。 My code is as follows: 我的代码如下:

#I search for tweets to my bot's handle
twt = api.search(q='@samplehandle')

#list of specific strings we want to omit from responses
a = ['java',
     'swift']


#list of specific strings I want to check for in tweets and reply to
t = ['I love code',
     'python rocks',
     'javascript']

for c in twt:
    for b in a:
            if b not in c.text:
                for s in twt:
                    for i in t:
                        if i in s.text:
                            sn = s.user.screen_name
                            m = "@%s This is a lovely tweet" % (sn)
                            s = api.update_status(m, s.id)

            else:
                print "Null"

Thank you 谢谢

Instead of having a ton of nested for loops your program will be much more manageable if you make use of a function to determine if a tweet contains words in a specific list. 如果您使用函数来确定某条推文是否包含特定列表中的单词,那么您的程序将比一堆嵌套的for循环好得多。 I also changed your variable names because there's no way to work with a, b, c, d, 我还更改了您的变量名称,因为无法使用a,b,c,d,

#list of specific strings we want to omit from responses
badWords = ['java', 'swift']

#list of specific strings I want to check for in tweets and reply to
goodWords = ['I love code', 'python rocks', 'javascript']


def does_contain_words(tweet, wordsToCheck):
    for word in wordsToCheck:
        if word in tweet:
            return True
    return False

for currentTweet in twt:
    #if the tweet contains a good word and doesn't contain a bad word
    if does_contain_words(currentTweet.text, goodWords) and not does_contain_words(currentTweet.text, badWords):
        #reply to tweet

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM