Python 类型错误:“设置”对象不可下标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41718369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:29:27  来源:igfitidea点击:

TypeError: 'set' object is not subscriptable

pythonflask

提问by Tagc

my flask application gives a 'set' error I have been coding a RSS feed web app but currently am having an error that I cant figure out; this is my code :

我的 Flask 应用程序出现“设置”错误 这是我的代码:

import feedparser

from flask import Flask
from flask import render_template

app = Flask(__name__)

RSS = {"http://feeds.bbci.co.uk/news/rss.xml",
   "http://rss.iol.io/iol/news", "http://feeds.foxnews.com/foxnews/latest", "http://rss.cnn.com/rss/edition.rss"}
#error occurs here

@app.route("/")
@app.route("/<publication>")
def get_news(publication="bbc"):
    #ERROR OCCURS HERE
    feed = feedparser.parse(RSS[publication])
    first_article = feed['entries'][0]

    return render_template("home.html",
                       title=first_article.get("title"),
                       published=first_article.get("publication"),
                       summary=first_article.get("summary"))


if __name__ == "__main__":
    app.run(debug=True, port=5000)

I get my error at these two lines

我在这两行出现错误

    feed = feedparser.parse(RSS[publication])
    first_article = feed['entries'][0]

can't figure out the actual error

无法弄清楚实际错误

回答by Tagc

As Iron Fist points out, RSSis a set (which aren't subscriptable), although it looks as though you're trying to use it as a dictionary. Based on the default value you use for get_news, I'm hazarding a guess that you want something like this:

正如 Iron Fist 所指出的,RSS是一个集合(不可下标),尽管它看起来好像您正试图将其用作字典。根据您使用的默认值get_news,我冒昧地猜测您想要这样的东西:

RSS = {"bbc": "http://feeds.bbci.co.uk/news/rss.xml",
       "iol": "http://rss.iol.io/iol/news",
       "fox": "http://feeds.foxnews.com/foxnews/latest",
       "cnn": "http://rss.cnn.com/rss/edition.rss"}

回答by Tagc

As Iron Fist comments, it seems that you are defining a set and using it as dictionary. It's difficult to be sure, but for what I see in the code, RSS should actually be a dictionary, using the name of the feeder as key. So:

正如 Iron Fist 评论的那样,您似乎正在定义一个集合并将其用作字典。很难确定,但就我在代码中看到的而言,RSS 实际上应该是一个字典,使用 feeder 的名称作为关键字。所以:

RSS = {"bbc":"http://feeds.bbci.co.uk/news/rss.xml",
       "iol":"http://rss.iol.io/iol/news",
       "foxnews":"http://feeds.foxnews.com/foxnews/latest", 
       "cnn":"http://rss.cnn.com/rss/edition.rss"}