【问题标题】:how to use a flag to return only one group using findall- Python如何使用标志使用 findall-Python 仅返回一个组
【发布时间】:2016-04-29 19:07:28
【问题描述】:

我正在使用艺术代码(如果可能的话?),我正在尝试使用findall 检索第三组正则表达式。我在findall 上阅读了官方文档,发现它返回的元组有点缺乏,我想传入一个标志来返回第三组,而不是 3 组的元组(前两个是占位符)。链接某些内容以仅返回名称(第三组)而不是之后迭代的最有效方法是什么?

import re, requests

rgx = r"([<][TDtd][>])|(target[=]new[>])(?P<the_deceased>[A-Z].*?)[,]"

urls = {2013: "http://www.killedbypolice.net/kbp2013.html",
        2014: "http://www.killedbypolice.net/kbp2014.html",
        2015: "http://www.killedbypolice.net/" }

names_of_the_dead = []

for url in urls.values():
    response = requests.get(url)
    content = response.content
    people_killed_by_police_that_year_alone = re.findall(rgx, content)
    for dead_person in people_killed_by_police_that_year_alone:
        names_of_the_dead.append(dead_person)

#dead_americans_as_string = ",".join(names_of_the_dead)
#print("RIP, {} since 2013:\n".format(len(names_of_the_dead)))
#print(dead_americans_as_string)

In [67]: names_of_the_dead
Out[67]: 
[('', 'target=new>', 'May 1st - Dec 31st'),
 ('', 'target=new>', 'Ricky Junior Toney'),
 ('', 'target=new>', 'William Jackson'),
 ('', 'target=new>', 'Bethany Lytle'),
 ('', 'target=new>', 'Christopher George'),

【问题讨论】:

    标签: python regex python-2.7 request


    【解决方案1】:

    只需将第一个和第二个捕获组作为非捕获组。

    rgx = r"(?:[<][TDtd][>])|(?:target[=]new[>])(?P<the_deceased>[A-Z].*?)[,]"
    

    【讨论】:

      【解决方案2】:

      既然这是您要解析的 HTML 数据,为什么不使用专门的工具来解析它 - HTML Parser,例如 BeautifulSoup。想法是遍历表格行并获取第 4 列文本:

      import requests
      from bs4 import BeautifulSoup
      
      
      urls = {2013: "http://www.killedbypolice.net/kbp2013.html",
              2014: "http://www.killedbypolice.net/kbp2014.html",
              2015: "http://www.killedbypolice.net/" }
      
      names_of_the_dead = []
      
      for url in urls.values():
          response = requests.get(url)
          soup = BeautifulSoup(response.content, "html.parser")
      
          for row in soup.select("table tr")[2:]:
              cells = row.find_all("td")
              if len(cells) > 3:
                  names_of_the_dead.append(cells[3].text.split(",")[0].strip())
      
      print(names_of_the_dead)
      

      【讨论】:

      • 这就是我想要的亚历克。我认为这额外的 700 人不应该白白死去,因为他们的名字不被记住。非常感谢
      • 由于某种原因它不起作用。我这周会努力在 [17] 中: print(names_of_the_dead) []
      猜你喜欢
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多