【问题标题】:how to set a loop in this news api syntax如何在此新闻 api 语法中设置循环
【发布时间】:2021-05-16 18:49:42
【问题描述】:

您好,我目前正在制作一个语音助手,其中我已经导入了新闻 api,我想限制它说的新闻数量,就像我希望它只读取 3-4 条新闻一样 下面是代码:

elif 'news' in query:
             
            try:
                jsonObj = urlopen('https://newsapi.org/v2/top-headlines?country=in&apiKey={api-key}')
                data = json.load(jsonObj)
                i = 1
                 
                speak('here are some top news from the times of india')
                print('''=============== TIMES OF INDIA ============'''+ '\n')
                 
                for item in data['articles']:
                     
                    print(str(i) + '. ' + item['title'] + '\n')
                    print(item['description'] + '\n')
                    speak(str(i) + '. ' + item['title'] + '\n')
                    i += 1
            except Exception as e:
                 
                print(str(e))

【问题讨论】:

    标签: python json python-3.x api


    【解决方案1】:

    简单地将列表切片添加到您的数据列表中

    for item in data['articles'][0:3]:

    现在它只会阅读前 3 篇文章

    【讨论】:

      猜你喜欢
      • 2013-05-12
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 2019-08-27
      相关资源
      最近更新 更多