3

I'm trying to resize images from html code. This is one example:

My goal is to substitute " height="108" " and " width="150" with height and width 400. I've tried the following lines, though they don't seem to work:

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

Does anyone have a solution for this? Ps: I'm not that good at Regex... :)

8
  • Nooo... Do not parse/modify html/xml with regexes... Use tools like BeautifulSoup/XSLT/... Commented Mar 16, 2017 at 15:03
  • That does not quite answer my question, though i'll have a look into it :) Commented Mar 16, 2017 at 15:06
  • 3
    Python strings are immutable. The sub function returns a new string Commented Mar 16, 2017 at 15:07
  • Regexes are fine for this particular use case. Commented Mar 16, 2017 at 15:08
  • 1
    Possible duplicate of Re.sub not working for me Commented Mar 16, 2017 at 15:13

2 Answers 2

4

The reason it does not work is because strings are immutable, and you do not process the result. You can "solve" the issue with:

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

That being said it is a very bad idea to process HTML/XML with regexes. Say you have a tag <foo altwidth="1234">. Now you will change it to <foo altwidth="400"> do you want that? Probably not.

You can for instance use BeautifulSoup:

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)

Here we substitute all tags with a width attribute to width="400" and all tags with a height with height="400". You can make it more advanced by for instance only accepting <img> tags, like:

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)
Sign up to request clarification or add additional context in comments.

Comments

2

Seems to be working fine:

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

Note that re.sub does not mutate x:

>>> x
'<foo width="150" height="108">'
>>> y
'<foo width="400" height="108">'

Perhaps you want to do this instead:

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

1 Comment

Flagged a duplicate, by the way

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.