如何解决为什么在尝试运行我的 Twitter 天气机器人时会出现此错误
def reply_to_tweet():
print("retrieving and replying to tweets...")
last_seen_tweet = read_last_seen(FILE_NAME)
# mentions_timeline() returns a list of 20 most recent mentions
mentions = api.mentions_timeline(last_seen_tweet,tweet_mode="extended")
# reversing to read old tweets first
for mention in reversed(mentions):
print(str(mention.id) + " - " + mention.full_text)
last_seen_tweet = mention.id
store_last_seen(FILE_NAME,last_seen_tweet)
if "#" in mention.full_text.lower():
print("found #")
location = get_location(mention.full_text)
weather = get_weather(location)
# responding to tweet mention
api.update_status("@" + mention.user.screen_name + weather,mention.id)
def get_location(tweet):
# takes tweet and returns only the substring attached to hashtag
tweet_location = [i.strip("#") for i in tweet.split() if i.startswith("#")[0]]
tweet_location += " today weather.com"
return tweet_location
def get_weather(query):
for url in search(query,stop=1):
print("Results is " + url)
#this code sends a request and reads the webpage enclsed to the request
request = Request(url,headers={"User-Agent": "Mozilla/5.0"})
webpage = urlopen(request).read()
soup = BeautifulSoup(webpage,"html.parser")
try:
title = soup.findAll("span","today-daypart-title")[0].string
phrase = soup.findAll("span","today-daypart-wxphrase")[0].string
except IndexError as e:
forecast = (" could not find the weather,check back later")
print(e)
else:
forecast = (" forecast for " + title + " is " + phrase)
print(forecast)
return forecast
while True:
reply_to_tweet()
time.sleep(15)
然后我调用reply_to_tweet(),它搜索并显示推文但是当它尝试我得到的位置时: 类型错误:“bool”对象不可下标 我对机器人和 API 还很陌生,我正在使用 BeautifulSoup、googlesearch 和 tweepy
解决方法
看起来您正在尝试对布尔函数 startswith()
进行字符串切片,请尝试从 [0]
中删除 tweet_location = [i.strip("#") for i in tweet.split() if i.startswith("#")[0]]
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。