【问题标题】:Python re.search within for-loop to narrow results在 for 循环中进行 Python re.search 以缩小结果范围
【发布时间】:2013-06-24 14:15:30
【问题描述】:

为了帮助我了解 python 的基础知识,我正在编写一个脚本,该脚本将在每次发布新的 RedHat 内核勘误表时自动启动帮助台票证。

到目前为止,我可以创建一个所有勘误表的列表,每个勘误表都在自己的行中,作为多行变量。我希望接下来能够在完整的勘误表列表中搜索字符串中具有“内核”的项目,并将变量缩小到仅这些结果是我遇到问题的地方。我基本上可以找到“内核”的所有匹配项,但不是返回匹配项,它只是指出找到了一个匹配项。例如:

import re
import datetime
import urllib
from BeautifulSoup import BeautifulSoup

errata = 'http://rhn.redhat.com/errata/rhel-server-6-errata.html'

errata_data = urllib.urlopen(errata)
soup = BeautifulSoup(errata_data)

for syn in soup.findAll(attrs={'id' : re.compile("^synopsis")}):
        for line in syn:
                match = re.search("kernel", line, re.MULTILINE)
                print match

...对于不匹配的行,结果为“无”,并在找到匹配时指示某种指针,而不是打印匹配的行:

None
None
<_sre.SRE_Match object at 0x3f0ed30>
None
None
None

谢谢!

【问题讨论】:

  • 你想打印“比赛”是什么意思?你想打印这条线吗?

标签: python regex search for-loop beautifulsoup


【解决方案1】:

您正在寻找的是:

    for line in syn:
        match = re.search("kernel", line, re.MULTILINE)
        if match:  # gets rid lines that don't match, which return `None`
            print line

match 是一个匹配对象,其中包含一些有用的信息,例如匹配发生在什么位置。如果您只想打印匹配行,请使用print line

【讨论】:

  • 谢谢大卫,这解决了我的问题。
  • @user132791:当然。请注意,您可以通过单击旁边的绿色复选标记将答案标记为已接受。
猜你喜欢
  • 1970-01-01
  • 2018-12-20
  • 2022-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2022-06-13
  • 2018-03-09
相关资源
最近更新 更多