所以我有一个代码(可能效率很低,但那是另一个故事)从博客的html代码中提取url我把html放在一个.csv文件中,我把它放到python中,然后运行regex来获取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"'>

有没有办法让我从其他的胡说八道中找出链接呢另外,这只是regex搜索的一部分吗?谢谢!

最佳答案

这里的问题是re.search返回一个match object而不是匹配字符串,您需要使用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))

组([组1,…])
返回匹配的一个或多个子组如果有一个参数,则结果是一个字符串;如果有多个参数,则结果是一个元组,每个参数有一个项。如果没有参数,group1默认为零(返回整个匹配项)。如果groupN参数为零,则对应的返回值是整个匹配字符串;如果它在包含范围[1..99]内,则是匹配相应带圆括号组的字符串如果组号为负数或大于模式中定义的组数,则会引发索引器错误异常如果一个组包含在模式中不匹配的部分中,则相应的结果为“无”如果一个组包含在模式中多次匹配的部分中,则返回最后一个匹配。

10-02 04:57
查看更多