2014-01-31 35 views
0

想我也包含XML輸出如下字符串:在使用Python BeautifulSoup下劃線更換所有的連字符在XML標籤

<dept-details> 
    <dept-domain-id>1</dept-domain-id> 
    <dept-req-status>no-vacancies-present</dept-req-status> 
     . 
     . 
</dept-details> 

我想替換包含連字符的所有標籤( - )與下劃線(_),因爲我發現Beautiful Soup不允許你直接訪問標籤,除了使用find()外,this的帖子和this都是這樣。

所以我的目的是要包含標籤轉換 - _使帶子的樣子:

<dept_details> 
    <dept_domain_id>1</dept_domain_id> 
    <dept_req_status>no-vacancies-present</dept_req_status> 
     . 
     . 
</dept_details> 

我想知道我怎麼可以使用Python重的方法來做到這一點,或者如果我能做到這一點與BeautifulSoup直接,這將是偉大的!

在此先感謝

+2

BeautifulSoup非常適合HTML,對XML不太好。 –

+0

[etree](http://docs.python.org/2/library/xml.etree.elementtree.html)更適合xml解析。 –

回答

2

你需要在這裏正則表達式,請嘗試以下解決方案:

>>> s 
'<dept-details><dept-domain-id>1</dept-domain-id><dept-req-status>no-vacancies</dept-req-status></dept-details>' 
>>> re.sub('<(.*?)>', lambda x: x.group(0).replace('-','_'), s) 
'<dept_details><dept_domain_id>1</dept_domain_id><dept_req_status>no-vacancies</dept_req_status></dept_details>' 

有一些問題,正則表達式,例如,它也將取代有-任何屬性,但至少這將讓你去在正確的方向。

+0

非常感謝:)這似乎是訣竅。 – ARK

0

編輯:看到Burhan的答案,它好多了。

string = '<dept-details><dept-domain-id>1</dept-domain-id><dept-req-status>no-vacancies-present</dept-req-status></dept-details>' 

import re 

tags = re.finditer('<.*?-.*?>', string) 

for x in tags: 
    string = string[:x.span()[0]] + x.group(0).replace('-','_') + string[x.span()[1]:] 

print string 

其中字符串是您的實際XML代碼字符串。但絕對有更好的方法。

相關問題