2017-03-16 192 views
3

我正在嘗試從html代碼調整圖片大小。這是一個例子:Python re.sub替換html屬性

我的目標是替代" height="108"「和" width="150"用高度和寬度400 我已經試過以下行,但他們似乎沒有工作: ?

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

有沒有人有一個解決方案 PS:我沒那麼擅長的正則表達式... :)

+0

拿去......不解析/修改HTML/XML與正則表達式...等工具BeautifulSoup/XSLT/.. –

+0

這並不完全回答我的問題,雖然我會看看它:) – Tastro

+3

Python字符串是不可變的。子函數返回一個新的字符串 –

回答

4

它沒有理由工作是,因爲字符串是不可變的,並且您不處理結果。你可以在「解決」這個問題:

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

話雖這麼說這是一個非常糟糕的主意,以處理與正則表達式 HTML/XML。假設你有一個標籤<foo altwidth="1234">。現在你會改變它爲<foo altwidth="400">你想要嗎?可能不會。

可以例如使用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) 

在這裏,我們代替所有標籤與width屬性width="400"並與height="400"一個height所有標籤。你可以把它多由例如只接受<img>標籤先進,如:

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

看起來完全正常工作:

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

注意re.sub不發生變異X:

>>> x 
'<foo width="150" height="108">' 
>>> 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) 
+0

標記重複,順便說一句 –