2013-02-05 4 views
2

"name : value"가 포함 된 목록에 name : value 요소가있는 텍스트 파일을 구문 분석하려고합니다. 다음과 같은 경우가 있습니다. 값이 여러 단어 일 때가 있습니다. 또는 심지어 여러 줄 및 구분 기호는 고정 된 단어 집합이 아닙니다. 여기에 여기에 값으로 구분 기호를 유지하면서 파이썬 정규식 문자열을 분할하면서 문자열을 분할

["price:44.55", "name:John Doe", "title:Super Widget", "description:This widget slices, dices, and drives your kids to soccer practice\r\nIt even comes with Super Widget Mini!"] 

내가 ...

지금까지 시도했습니다 무엇

listing="price:44.55 name:John Doe title:Super Widget description:This widget slices, dices, and drives your kids to soccer practice\r\nIt even comes with Super Widget Mini! 

내가 반환 할 것은 ... 내가 함께 작동하도록 노력하고있어의 예

details = re.findall(r'[\w]+:.*', post, re.DOTALL) 
["price:", "44.55 name:John Doe title:Super Widget description:This widget slices, dices, and drives your kids to soccer practice\r\nIt even comes with Super Widget Mini!"] 

내가 원하는 것은 아닙니다. 또는 ...

내가 원하는 것은 아닙니다. 또는 ...

details = re.split(r'([\w]+:)', post) 
["", "price:", "44.55", "name:", "John Doe", "title:", "Super Widget", "description:", "This widget slices, dices, and drives your kids to soccer practice\r\nIt even comes with Super Widget Mini!"] 

더 가깝지만 주사위는 없습니다. 또한 빈 목록 항목을 처리 할 수 ​​있습니다. 그래서, 기본적으로, 내 질문은 re.split() 값으로 구분 기호를 유지하는 방법 또는 re.findall() 너무 욕심이 심하거나 인색 한 유지하는 방법은 무엇입니까?

미리 읽어 주셔서 감사합니다.

답변

5

사용 예견 주장 : 일부 단어가있는 경우

>>> re.split(r'\s(?=\w+:)', post) 
['price:44.55', 
'name:John Doe', 
'title:Super Widget', 
'description:This widget slices, dices, and drives your kids to soccer practice\r\nIt even comes with Super Widget Mini!'] 

은 물론, 여전히 실패는 당신의 가치에 콜론 바로 뒤에. 파벨의 대답 @

+0

일했다! 감사! 나는 look-ahead 또는 look-behind 물건을 잘 이해하지 못했다. 정말 도움을 주셔서 감사합니다! – user2044258

2

은 좋네요,하지만 당신은 당신의 마지막 시도의 결과를 함께 병합 수 :

# kill the first empty bit 
if not details[0]: 
    details.pop(0) 

return [a + b for a, b in zip(details[::2], details[1::2])] 
+0

나는 이렇게하는 것에 대해 생각해 보았지만, 너무 성가신 것 같았지만 대답에 감사드립니다! – user2044258

관련 문제