Python:使用JSON API链接通过正则表达式显示命名捕获组

问题描述 投票:0回答:1

我使用正则表达式显示正确的命名捕获组时遇到问题。我已经有正则表达式公式来捕获该组。这是我的regex链接显示。通过查看链接,我试图以绿色突出显示文本。

绿色部分是包含链接的JSON API中的页面标题。它们被标记为“文章”。到目前为止我所做的是解析JSON以获取文章列表并显示它。有些文章有多个页面,我只是想显示第一页。这就是我使用REGEX的原因,因为我在这里处理大文件。我试图让正则表达式的绿色部分显示在我的函数中。这是我的工作代码没有正则表达式实现的link。这是我到目前为止尝试使用的代码:

import json
import requests
import re

link = "https://wikimedia.org/api/rest_v1/metrics/pageviews/top/en.wikiversity/all-access/2018/01/10"

def making_data(link):
  response = requests.get(link, [])
  data = response.json()
  json_data = data['items']
  articles_list = []

  whole_re= re.compile(r'^[^\/].*')
  rx = re.compile(r'(^[^\/]+)')
  for items in json_data:
      articles = items['articles']
      #Iterate over the list of articles
      for article in articles:
          m = whole_re.match(article)
          if m: 
            articles_list.append(m)
            articles = article.get("article")
            search_match = rx.match(article)
            if search_match: 
              print("Page: %s" % articles)

  return sorted(articles_list)

making_data(link) 

我一直在用正则表达式出错。我想我用JSON和正则表达式实现了这个错误。

我希望输出只显示提供的正则表达式链接中以绿色突出显示的内容,之后不显示以下文本。

Page: Psycholinguistics
Page: Java_Tutorial
Page: United_States_currency  

我希望这一切都有道理。我感谢所有的帮助。

python json regex-group
1个回答
1
投票

如果您打印article,您将看到它是字典格式。你的正则表达式不是什么错误,而是你引用article的方式。

您打算从您链接的原始代码中引用article_title = article.get("article"),我相信。

另一件将成为问题的事情是在循环中间重命名articles。我为你做了一些编辑,但你需要根据你想要的确切用法和结果进行一些改进。

您可以使用.group(1)引用匹配对象组

import json
import requests
import re

link = "https://wikimedia.org/api/rest_v1/metrics/pageviews/top/en.wikiversity/all-access/2018/01/10"

def making_data(link):
  response = requests.get(link, [])
  data = response.json()
  json_data = data['items']
  articles_list = []

  whole_re= re.compile(r'^[^\/].*')
  rx = re.compile(r'(^[^\/]+)')
  for items in json_data:
      articles = items['articles']
      #Iterate over the list of articles
      for article in articles:          
          article_title = article.get("article")
          m = whole_re.match(article_title)
          if m: 
            articles_list.append(m[0])
            search_match = rx.match(article_title)
            if search_match:
              print("Page: %s" % search_match.group(1))

  return sorted(articles_list)

making_data(link)
© www.soinside.com 2019 - 2024. All rights reserved.