![](/img/trans.png)
[英]Regex: Allow a string that contains “foo” but not if that same string also contains “bar”
[英]Python if string contains “foo” do this
我有一個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"
謝謝
如果您使用函數來確定某條推文是否包含特定列表中的單詞,那么您的程序將比一堆嵌套的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.