我对python还不太熟悉。我有个错误需要理解。
代码:
配置文件:
# Vou definir os feeds
feeds_updates = [{"feedurl": "http://aaa1.com/rss/punch.rss", "linktoourpage": "http://www.ha.com/fun.htm"},
{"feedurl": "http://aaa2.com/rss.xml", "linktoourpage": "http://www.ha.com/fun.htm"},
{"feedurl": "http://aaa3.com/Heaven", "linktoourpage": "http://www.ha.com/fun.htm"},
{"feedurl": "http://aaa4.com/feed.php", "linktoourpage": "http://www.ha.com/fun.htm"},
{"feedurl": "http://aaa5.com/index.php?format=feed&type=rss", "linktoourpage": "http://www.ha.com/fun.htm"},
{"feedurl": "http://aaa6.com/rss.xml", "linktoourpage": "http://www.ha.com/fun.htm"},
{"feedurl": "http://aaa7.com/?format=xml", "linktoourpage": "http://www.ha.com/fun.htm"},
{"feedurl": "http://aaa8/site/component/rsssyndicator/?feed_id=1", "linktoourpage": "http://www.ha.com/fun.htm"}]
twitterC.py公司
# -*- coding: utf-8 -*-
import config # Ficheiro de configuracao
import twitter
import random
import sqlite3
import time
import bitly_api #https://github.com/bitly/bitly-api-python
import feedparser
...
# Vou escolher um feed ao acaso
feed_a_enviar = random.choice(config.feeds_updates)
# Vou apanhar o conteudo do feed
d = feedparser.parse(feed_a_enviar["feedurl"])
# Vou definir quantos feeds quero ter no i
i = range(8)
print i
# Vou meter para "updates" 10 entradas do feed
updates = []
for i in range(8):
updates.append([{"url": feed_a_enviar["linktoourpage"], "msg": d.entries[i].title + ", "}])
# Vou escolher ums entrada ao acaso
print updates # p debug so
update_to_send = random.choice(updates)
print update_to_send # Para efeitos de debug
以及有时由于随机性而出现的错误:
Traceback (most recent call last):
File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 77, in <module>
updates.append([{"url": feed_a_enviar["linktoourpage"], "msg": d.entries[i].title + ", "}])
IndexError: list index out of range
我还没说到错误,列表“feeds_updates”是一个包含8个元素的列表,我认为它的声明很好,随机选择8个元素中的一个。。。
有人能告诉我这里发生了什么吗?
很抱歉我的英语不好。
谨致问候
使用
range
进行迭代几乎总是不是最好的方法。在Python中,您可以直接对列表、dict、set等进行迭代:显然,
d.entries[i]
会触发错误,因为该列表包含的项少于8个(feeds_updates
可能包含8个,但您不会在该列表上迭代)。d.entries
少于8个元素。直接在d.entries
上迭代,而不是在某些断开连接的范围上迭代。相关问题 更多 >
编程相关推荐