2014-01-31 1 views
0

가정 해 보겠습니다 I했습니다 다음과 같이 XML 출력을 포함하는 문자열 :파이썬에서 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> 

나는 그것을 할 수 있다면 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 

여기서 string은 실제 XML 코드 문자열입니다. 확실히 좋은 방법이 있습니다.

현재 정규 표현식을 필요
관련 문제