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

标签 python regex

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

<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>
>>> 

关于python - 如何使用python Regular使宽度和高度x2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5877717/

相关文章:

java - 为什么在 `(.+?)`后面加一个空格就可以完全改变结果

regex - 我应该使用什么命令行工具使用复杂的正则表达式从文件中提取字符串

Python - 从url获取图像名称和扩展名不以文件文件扩展名结尾

python - 即使我安装了 Web3.py(我使用的是 venv),也没有名为 "web3"的模块

java - Android android.util.Patterns.EMAIL_ADDRESS 奇怪的行为

c# - 正则表达式行尾和字符串终止符!

python - 带迭代的二维字典

python - 在 Pandas 中分隔和堆叠列(Python 3.4)

使用 cpu 查找前 5 个进程的 Python 代码

从 R 中的 .sdf 文件中提取唯一字段的正则表达式