2014-06-19 1 views
0

저는 이메일 본문에서 html을 포함하는 내부 dict에 dict 내에 dict이있는 매우 큰 defaultdict가 있습니다. 난 내부 dict 내에서 HTTP 문자열을 반환하고 싶습니다. 그걸 추출하는 가장 좋은 방법은 뭔가요?defaultdict의 값에 액세스하여 URL 부분을 제거합니다.

regex를 사용하기 전에 사전을 다른 데이터 구조로 변환해야합니까? 더 좋은 방법이 있습니까? 나는 여전히 Python을 처음 접했고 어떤 포인터에 감사하고있다. 내가 작업하고있는 무슨 예를 들어

:

작동하지 않았다 나는 defaultdict에 re.findall을 사용하려고했습니다
defaultdict(<type 'dict'>, {16: {u'SEQ': 16, u'RFC822': u'Delivered-To: 
[email protected]  LOTS MORE HTML until http://the_url_I_want_to_extract.com' }} 

한 가지 :

confirmation_link = re.findall('Click this link to confirm your registration:<br />" 
(.*?)"', body) 

for conf in confirmation_link: 
    print conf 

오류 :

line 177, in findall 
return _compile(pattern, flags).findall(string) 
TypeError: expected string or buffer 
+2

은 당신이 지금까지 시도 했습니까? 어떤 코드가 있습니까? 어떤 문제가 있습니까? –

+0

re를 직접 사용하는 것과 같은 몇 가지 시도를 해봤습니다. 몸에 iteritems 및 key.startswith 찾고 있었지만, 그냥 갈 방향으로 고투. 나는 시도한 것들 중 몇 가지를 포스트에 적용 할 것이다. – Michael

+0

특정 문제를 일으키고 설명하는 코드로 질문을 업데이트하십시오. –

답변

1

해당 va에 대해 사전을 반복하면 정규 표현식 만 사용할 수 있습니다 루 :

import re 

d = defaultdict(<type 'dict'>, {16: {u'SEQ': 16, u'RFC822': u'Delivered-To: [email protected]  LOTS MORE HTML until http://the_url_I_want_to_extract.com' }} 

for k, v in d.iteritems(): 
    #v is the dictionary that contains your html string: 
    str_with_html = v['RFC822'] 

    #this regular expression starts with matching http, and then 
    #continuing until a white space character is hit. 
    match = re.search("http[^\s]+", str_with_html) 
    if match: 
     print match.group(0) 

는 출력 :

이 가
http://the_url_I_want_to_extract.com 
+0

Martin 고맙습니다. 정말로 감사드립니다. 사전에 iteritems로 작동하고 노는, 나는 새로운 것을 배웠습니다. :) – Michael