gpt4 book ai didi

Python 如果字符串包含 "foo"则执行此操作

转载 作者:太空宇宙 更新时间:2023-11-04 00:50:58 25 4
gpt4 key购买 nike

我有一个 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

关于Python 如果字符串包含 "foo"则执行此操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37199183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com