Python在for循环中重新搜索以缩小结果



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

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

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
None
<_sre.SRE_Match object at 0x3f0ed30>
None
None
None

谢谢!

您要查找的是:

    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

最新更新