python - 为什么我在尝试运行我的 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(),它搜索并显示推文,但是当它尝试我得到的位置时:TypeError:'bool'对象不可下标我对机器人和api相当陌生,我正在使用BeautifulSoup,googlesearch和tweepy
解决方案
看起来您正在尝试对 bool 函数进行字符串切片startswith()
,请尝试[0]
从 tweet_location = [i.strip("#") for i in tweet.split() if i.startswith("#")[0]]
.
推荐阅读
- c# - 当从 C# 应用程序调用时,为什么在 f# 中实现的类型与 C# 类型的行为不同?
- joomla - 如何获取 Joomla 组件参数值?
- excel - Excel,选择一个数据只显示数据
- android - Ionic2 如何处理屏幕阅读器文本?
- python - 使用 python 在 GUI 上导入 json 文件。获取 JSONDecodeError
- python-3.x - Oracle 客户端在 Python 脚本中的重要性是什么?
- python - for循环列表递增
- php - 启用 intl 扩展以使用 CakePHP
- ios - 在 Xcode 错误代码中使用 Alamo fire 向烧瓶服务器发送请求:-1004
- android - 检测我的设备的蓝牙何时被禁用