问题描述
我创建了一个机器人,它可以与用户的推文互动,并在 # 中回复用户推文所在位置的天气,例如“伦敦的天气怎么样”。然后,机器人将回复伦敦目前的天气情况。
当我运行机器人时,它运行良好并找到获取天气数据的 URL 并存储推文,但是当它需要回复天气时,我得到一个超出范围的列表索引。
代码:
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
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)
retrieving and replying to tweets...
1386417114316169219 - @UniProjectbot #Birmingham
found #
Results is https://weather.com/en-GB/weather/today/l/Birmingham+England?canonicalCityId=de781cf30dc9d9dbea1ed33096e3729fe38d4023bb06259589d311d034072b9d
list index out of range
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)