Python 为什么我在尝试运行我的Twitter天气机器人时会出现此错误
然后我调用reply_to_tweet(),它会搜索并显示tweet,但当它尝试我获得的位置时: TypeError:“bool”对象不可下标Python 为什么我在尝试运行我的Twitter天气机器人时会出现此错误,python,api,twitter,bots,openweathermap,Python,Api,Twitter,Bots,Openweathermap,然后我调用reply_to_tweet(),它会搜索并显示tweet,但当它尝试我获得的位置时: TypeError:“bool”对象不可下标 我对机器人程序和api相当陌生,我正在使用BeautifulSoup、googlesearch和tweepy看起来你正在尝试对bool函数startswith(),尝试从tweet\u位置=[I.strip(“#”)中删除[0],如果I.startswith(“#”)中的I.split()[0]]请编辑您的帖子,将获取天气()的代码添加到以及回复到twe
我对机器人程序和api相当陌生,我正在使用BeautifulSoup、googlesearch和tweepy看起来你正在尝试对bool函数
startswith()
,尝试从tweet\u位置=[I.strip(“#”)中删除[0]
,如果I.startswith(“#”)中的I.split()[0]]
请编辑您的帖子,将获取天气()的代码添加到以及回复到tweet()
?谢谢您的回答,我尝试了您建议的内容,但出现了一个新错误“TypeError:quote\u from\u bytes()expected bytes”@J\u Simm请尝试一下tweet_location=[i.strip(“#”)表示我在tweet.split()中的位置,如果i.startswith(“#”)表示[0]
谢谢,这很烦人,因为这只是一件小事,但由于某些原因,它不会得到天气,它不会产生错误,只是说“列表索引超出范围”。谢谢你的帮助。你有没有想过为什么会出现这个索引错误?@J_Simm你到底想通过迭代“tweet_location”来提取什么?
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)