Skip to main content
 首页 » 编程设计

python之如何使用python Regular使宽度和高度x2

2025年05月04日11langtianya

我必须做很多工作才能像这样改变:

<img src = "/" height="111" width="10" /> 

到

<img src = "/" height="222" width="20" /> 

所以我想用python Regular 这是我的代码:

import re 
 
s = '<img src = "werwerwe" height="111" width="10" />' 
 
def a(x): 
    print x.group(2) 
    print x.group(4) 
 
ss = re.sub(r'''<img.*(width\s*="?(\d+)"?)*\s*(height\s*="?(\d+)"?)*''',a, s) 
 
print ss 

那我该怎么办呢,

谢谢

更新:

现在可以了:

import re 
 
s = '<img src = "/" height="111" width="10" />' 
 
 
def a(x): 
    b = x.group(0) 
    b = b.replace(x.group(1),str(int(x.group(1))*2)) 
    b = b.replace(x.group(2),str(int(x.group(2))*2)) 
    return b 
 
ss = re.sub(r'''<img.*?height=\"(\d+)\".*?width=\"(\d+)\"[^>]*>''',a, s) 
 
print ss 

请您参考如下方法:

不要使用正则表达式来解析 HTML。使用 BeautifulSoup

>>> from BeautifulSoup import BeautifulSoup 
>>> ht = '<html><head><title>foo</title></head><body><p>whatever: <img src="foo/img.png" height="111" width="22" /></p><ul><li><img src="foo/img2.png" height="32" width="44" /></li></ul></body></html>' 
>>> soup = BeautifulSoup(ht) 
>>> soup 
<html><head><title>foo</title></head><body><p>whatever: <img src="foo/img.png" height="111" width="22" /></p><ul><li><img src="foo/img2.png" height="32" width="44" /></li></ul></body></html> 
>>> soup.findAll('img') 
[<img src="foo/img.png" height="111" width="22" />, <img src="foo/img2.png" height="32" width="44" />] 
>>> for img in soup.findAll('img'): 
...     ht = int(img['height']) 
...     wi = int(img['width']) 
...     img['height'] = str(ht * 2) 
...     img['width'] = str(wi * 2) 
...      
...  
>>> print soup.prettify() 
<html> 
 <head> 
  <title> 
   foo 
  </title> 
 </head> 
 <body> 
  <p> 
   whatever: 
   <img src="foo/img.png" height="222" width="44" /> 
  </p> 
  <ul> 
   <li> 
    <img src="foo/img2.png" height="64" width="88" /> 
   </li> 
  </ul> 
 </body> 
 </html> 
>>>