开发者

php regular expression convert to python code

i have this code written in php, and i want to convert it into python code

$title_regex = "/<title>(.+)<\/title>/i";
preg_match_all($title_regex, $string, $title, PREG_PATTERN_ORDER);
$url_title = $title[1];

/// fecth decription
$tags = get_meta_tags($url);

// fetch images
$image_regex = '/<img[^>]*'.'src=[\"|\'](.*)[\"|\']/Ui开发者_高级运维';
preg_match_all($image_regex, $string, $img, PREG_PATTERN_ORDER);
$images_array = $img[1];

i have tried this .. but it give me errors in pics part

import re
out=Data #web site html page ..
title_regex = "/<title>(.+)<\/title>/i" #no need for this .. un used 
m = re.search("<title>(.+)<\/title>", out)
print "title",m.group(1)
#for pics i have tried this but it give me error ..
pics = re.match(r"/<img[^>]*'.'src=[\"|\'](.*)[\"|\']/Ui", out)#the conversion is not correct  
print "grop",pics.group(1)

my full code

import re
import urllib
print "Start"
url="http://www.deviantart.com"
data=urllib.urlopen(url)
out=data.read()
print 
title_regex = "/<title>(.+)<\/title>/i"
m = re.search("<title>(.+)<\/title>", out)
print "first",m
print "title=",m.group(1)

title_regex = "/<title>(.+)<\/title>/i"

pics = re.match(r"/<img[^>]*src=[\"|\'](.*)[\"|\']/Ui", out)

print "pics>>",pics.group(1)

how i can convert a php re>>"/]*'.'src=\"|\'[\"|\']/Ui" to a python re ?


the regular expression probably did not find anything.

try this : also remove the /Ui at the end

import re
out=Data #web site html page ..
title_regex = "/<title>(.+)<\/title>/i" #no need for this .. un used 
if m is not None:  #  NEW  <----------------
   m = re.search("<title>(.+)<\/title>", out)
print "title",m.group(1)
#for pics i have tried this but it give me error ..
pics = re.match(r"<img[^>]*src=[\"|\'](.*)[\"|\']", out)
if pics is not None: # NEW <----------------
   print "grop",pics.group(1)

for you 2nd question try this

for filename in pics.groups():
    print filename


Working version .. display all images from a given web site using tag IMG src > code:

  import re
  import urllib
  print "Start"
  url="http://www.deviantart.com"
  data=urllib.urlopen(url)
  out=data.read()
  print 
  title_regex = "/<title>(.+)<\/title>/i"
  m = re.search("<title>(.+)<\/title>", out)
  print "first",m
  print "grop",m.group(1)

  title_regex = "/<title>(.+)<\/title>/i"

  pics = re.compile(r"<IMG[^>]*src=([^>]*[^/])")#Change IMG tag 
  allpics=pics.findall(out)
  print "found",pics
  for mypic in allpics:
     print "< IMG src=",mypic

thanks all

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜