Python re.sub替换html属性

Python re.sub替换html属性,python,html,regex,Python,Html,Regex,我正在尝试根据html代码调整图像大小。这是一个例子: 我的目标是用高度和宽度400替换“height=”108“”和“width=”150“。 我试过以下几行,但似乎不起作用: re.sub(r'width="[0-9]{2,4}"','width="400"',x) re.sub(r'height="[0-9]{2,4}"','height="400"',x) 有人能解决这个问题吗? 附:我不太擅长正则表达式…:)似乎工作正常: >>> x = '<foo wid

我正在尝试根据html代码调整图像大小。这是一个例子:

我的目标是用高度和宽度400替换
“height=”108“
”和
“width=”150“
。 我试过以下几行,但似乎不起作用:

re.sub(r'width="[0-9]{2,4}"','width="400"',x)
re.sub(r'height="[0-9]{2,4}"','height="400"',x)
有人能解决这个问题吗?
附:我不太擅长正则表达式…:)

似乎工作正常:

>>> x = '<foo width="150" height="108">'
>>> import re
>>> y = re.sub(r'width="[0-9]{2,4}"','width="400"',x)
>>> y
'<foo width="400" height="108">'
也许您想这样做:

x = re.sub(r'width="[0-9]{2,4}"','width="400"',x)
x = re.sub(r'height="[0-9]{2,4}"','height="400"',x)

它不起作用的原因是,因为字符串是不可变的,并且您不处理结果。您可以通过以下方法“解决”该问题:

x = re.sub(r'width="[0-9]{2,4}"','width="400"',x)
x = re.sub(r'height="[0-9]{2,4}"','height="400"',x)
在这里,我们用
width
属性替换all标记为
width=“400”
,用
height=“400”
替换所有
高度的标记为
height=“400”
。例如,您可以通过仅接受
标记使其更高级,例如:

soup = BeautifulSoup(x,'lxml')

for tag in soup.findAll('img',attrs={"width":True})
    tag.width = 400
for tag in soup.findAll('img',attrs={"height":True})
    tag.height = 400
x = str(soup)
soup=BeautifulSoup(x,'lxml')
对于soup.findAll('img',attrs={“width”:True})中的标记
标签宽度=400
对于soup.findAll('img',attrs={“height”:True})中的标记
标记高度=400

x=str(汤)
Nooo…不要用正则表达式解析/修改html/xml…使用BeautifulSoup/XSLT/…之类的工具,这并不能完全回答我的问题,尽管我会仔细研究一下:)Python字符串是不可变的。子函数返回一个新的字符串正则表达式对于这个特定的用例来说是可以的。顺便说一句,标记重复的可能重复
soup = BeautifulSoup(x,'lxml')

for tag in soup.findAll(attrs={"width":True})
    tag.width = 400
for tag in soup.findAll(attrs={"height":True})
    tag.height = 400
x = str(soup)
soup = BeautifulSoup(x,'lxml')

for tag in soup.findAll('img',attrs={"width":True})
    tag.width = 400
for tag in soup.findAll('img',attrs={"height":True})
    tag.height = 400
x = str(soup)