分析一段文本并打印关键词后的短语

2024-09-23 04:35:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序,使用newsapi和wx根据需要获取与某些主题相关的标题

但是函数会输出这样一个文本块(如果搜索单词“Tesla”):

{'status': 'ok', 'totalResults': 14, 'articles': [{'source': {'id': 'techcrunch', 'name': 'TechCrunch'}, 'author': 'Darrell Etherington', 'title': "Tesla focuses on service with 25 new service centers in Q2, rate of new openings to 'increase'", 'description': 'Tesla is set to ramp up the rate at which it opens new service facilities aggressively, according to CEO Elon Musk’s guidance on the company’s Q2 2019 earnings call. In total, Tesla opened 25 new service centers during the quarter, and added 100 new service v…', 'url': 'https://techcrunch.com/2019/07/24/tesla-focuses-on-service-with-25-new-service-centers-in-q2-rate-of-new-openings-to-increase/', 'urlToImage': 'https://techcrunch.com/wp-content/uploads/2019/07/GettyImages-1150569888.jpg?w=592', 'publishedAt': '2019-07-24T23:36:47Z', 'content': 'Tesla is set to ramp up the rate at which it opens new service facilities aggressively, according to CEO Elon Musk’s guidance on the company’s Q2 2019 earnings call. In total, Tesla opened 25 new service centers during the quarter, and added 100 new service v… [+2866 chars]'}, {'source': {'id': 'the-verge', 'name': 'The Verge'}, 'author': "Sean O'Kane", 'title': 'Tesla’s longtime CTO is stepping down', 'description': 'Lon.....

我想让所有的标题都显示在一个列表中,这样我就不必解析大量的文本了

我的想法是搜索所有出现的“title”:然后在每次出现后打印引号中的每个短语。有什么建议吗

注: 生成此文本的代码是:

def NewsSearch(self, event):
    newsapi = NewsApiClient(api_key='8ab524f489d34b278ad537389c789498')
    input = self.tc4.GetValue()
    top_headlines = newsapi.get_top_headlines(q=input)
    print(top_headlines)

其中输入是从wx中的TextCtrl面板收集的,通过将按钮单击绑定到函数来调用函数


Tags: theto文本newratetitleison
2条回答

头条新闻是一本字典,你可以从每一篇文章中提取标题并把它们放到一个列表中

articles = top_headlines['articles']
titles = [article['title'] for article in articles]

以下摘录是您需要的部分:

 'articles': [{'source': {'id': 'techcrunch', 'name': 'TechCrunch'}, 'author': 'Darrell Etherington', 'title': "Tesla focuses on service with 25 new service centers in Q2, rate of new openings to 'increase'"

因此top_headlines["articles"]是文章列表,是具有单个key:value pair 的"source": another_dict,您可以通过以下方式获得标题:

[article["source"]["title"] for article in top_headlines["articles"]]

相关问题 更多 >