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

时间:2016-05-12 23:46:30

标签: python twitter tweepy

我有一个Twitter机器人响应包含数组t中某些字符串的推文。我正在尝试编写一个条件语句,限制它响应包含来自另一个数组a的字符串的推文。理论上它应该有效,但事实并非如此。机器人忽略了if / else语句。我的代码如下:

#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"

谢谢

1 个答案:

答案 0 :(得分:3)

如果您使用函数来确定推文是否包含特定列表中的单词,那么您的程序将更易于管理,而不是拥有大量嵌套for循环。我也改变了你的变量名,因为没有办法使用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