Python:隔离re.search结果

4

我有一段代码(可能非常低效,但这是另一个故事),它从博客的HTML代码中提取URL。我将HTML保存在.csv文件中,然后将其放入Python中,并运行正则表达式以获取URL。以下是代码:

import csv, re # required imports

infile = open('Book1.csv', 'rt')  # open the csv file
reader = csv.reader(infile)  # read the csv file


strings = [] # initialize a list to read the rows into

for row in reader: # loop over all the rows in the csv file 
    strings += row  # put them into the list

link_list = []  # initialize list that all the links will be put in
for i in strings:  #  loop over the list to access each string for regex (can't regex on lists)

    links = re.search(r'((https?|ftp)://|www\.)[^\s/$.?#].[^\s]*', i) # regex to find the links
    if links != None: # if it finds a link..
        link_list.append(links) # put it into the list!

for link in link_list: # iterate the links over a loop so we can have them in a nice column format
    print(link)

这个代码是有效的,不过当我打印结果时,它的格式是:

<_sre.SRE_Match object; span=(49, 80), match='http://buy.tableausoftware.com"'>
<_sre.SRE_Match object; span=(29, 115), match='https://c.velaro.com/visitor/requestchat.aspx?sit>
<_sre.SRE_Match object; span=(34, 117), match='https://www.tableau.com/about/blog/2015/6/become->
<_sre.SRE_Match object; span=(32, 115), match='https://www.tableau.com/about/blog/2015/6/become->
<_sre.SRE_Match object; span=(76, 166), match='https://www.tableau.com/about/blog/2015/6/become->
<_sre.SRE_Match object; span=(9, 34), match='http://twitter.com/share"'>

有没有办法让我只从其他无关的内容中提取链接?这是正则表达式搜索的一部分吗?谢谢!

1个回答

2
这里的问题在于re.search返回的是一个匹配对象而不是匹配字符串,您需要使用group属性来访问您想要的结果。
如果您想要所有捕获的组,可以使用groups属性,对于特定的组,可以将期望的组号传递给它。
在这种情况下,似乎您想要整个匹配,因此可以使用group(0):
for i in strings:  #  loop over the list to access each string for regex (can't regex on lists)

    links = re.search(r'((https?|ftp)://|www\.)[^\s/$.?#].[^\s]*', i) # regex to find the links
    if links != None: # if it finds a link..
        link_list.append(links.group(0))

group([group1, ...])

返回匹配的一个或多个子组。如果只有一个参数,则结果是一个字符串;如果有多个参数,则结果是一个包含每个参数一项的元组。如果没有参数,group1默认为零(整个匹配将被返回)。如果groupN参数为零,则相应的返回值是整个匹配的字符串;如果它在包括范围[1..99]内,则它是与相应括号分组匹配的字符串。如果组号为负数或大于模式中定义的组数,则会引发IndexError异常。如果组包含在未匹配的模式部分中,则相应结果为None。如果组包含在匹配多次的模式部分中,则返回最后一个匹配。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接