2013-11-26 18 views
0

我目前有一段代码主要运行,因为我期望它只打印出原始列表和已被过滤的代码。基本上我想要做的是从网页中读取URL并将它们存储到列表中(称为匹配,这部分工作正常),然后将该列表过滤到新列表中(称为fltrmtch),因为原始包含所有额外的href标签等。Python的正则表列入另一个列表

例如目前它只会B之后打印出A和B,但林:

Core Development '

' http://docs.python.org/devguide/“),

赫雷什代码:

url = "URL WOULD BE IN HERE BUT NOT ALLOWED TO POST MULTIPLE LINKS" #Name of the url being searched 
webpage = urllib.urlopen(url) 

content = webpage.read() #places the read url contents into variable content 


import re # Imports the re module which allows seaching for matches. 
import pprint # This import allows all listitems to be printed on seperate lines. 

match = re.findall(r'\<a.*href\=.*http\:.+', content)#matches any content that begins with a href and ands in > 


def filterPick(list, filter): 
    return [(l, m.group(1)) for l in match for m in (filter(l),) if m] 

regex=re.compile(r'\"(.+?)\"').search 
fltrmtch = filterPick(match, regex) 

try: 

    if match: # defines that if there is a match the below is ran. 
     print "The number of URL's found is:" , len(match) 
     match.sort() 
     print "\nAnd here are the URL's found: " 
     pprint.pprint(fltrmtch) 


except: 
     print "No URL matches have been found, please try again!" 

任何帮助将 非常感激。

预先感谢您。

UPDATE:谢谢你不过颁发的答案,我设法找到破绽

回报[(1,1- m.group(1))l在匹配米(过滤器(L))如果m]

我只是不得不从[(1,m.group(1)))中删除1。再次感谢。

回答

0

看起来代码的底部大部分都是从顶部捕捉错误,并且您提供的正则表达式没有捕获组。这是修改后的例子:

import re 
url = "www.site.com" # place real web address here 
# read web page into string 
page = urllib.urlopen(url).read() 
# use regex to extract URLs from <a href=""> patterns 
matches = re.findall(r'''\<a\s[^\>]*?\bhref\=(['"])(.+?)\1[^\>]*?\>''', page, re.IGNORECASE) 
# keep only the second group of positive matches 
matches = sorted([match.group(2) for match in matches if match]) 
# print matches if they exist 
if matches: 
    print("The number of URL's found is:" + str(len(matches))) 
    print("\nAnd here are the URL's found:") 
    # print each match 
    print('\n'.join(matches)) 
else: 
    print 'No URL matches have been found, please try again!' 
相关问题