2017-11-22 1 views
0

이 분할 (팬더없이) 어떤 쉬운 방법이 있나요 :Python3을 사용하여 전체 이름, 추천 및 이메일 주소가 포함 된 'from :'행을 쉽게 나눌 수 있습니까?

'이름 성 (id_192743918를) < [email protected]>'이 속으로

:

results = { 
    'name': 'First Last', 
    'comment': 'id_192743918', 
    'email': '[email protected]', 
} 

내가 할 수있는가 이 몇 가지 분리와 함께,하지만 나는 거기에 우아한 방법이있을 것이라고 확신합니다. 이 길을 따라

답변

3

뭔가를 할 수 있습니다

import re 
st = 'First Last (id_192743918) <[email protected]>' 
# split the string by (or) 
l = re.split(r'\(|\)', st) 
# strip whitespaces and replace <or> by empty space '' 
l = list(map(lambda x: re.sub(r'<|>','', x.strip()),l)) 

results = { 
    'name': l[0], 
    'comment': l[1], 
    'email': l[2], 
} 
+0

나를. 고맙습니다. – tazzytazzy

+0

@tazzytazzy 당신은 환영합니다 :). Stackoverflow에 대한 도움말을 계속 제공하도록 동기를 부여하기 위해 다른 답변도 투표하십시오. 나는 그들을 투표했다 :) – MedAli

1

나는 이것에 대한 정규식을 사용하십시오. 다음 코드에서는 정규 표현식과 사전을 결합하여 사전을 빠르게 생성합니다.

import re 

string = "First Last (id_192743918) <[email protected]>" 
print({['name','comment','email'][i]:g for i,g in enumerate(re.search("(\w+ \w+) \((.*?)\) <(.*?)>", string).groups())}) 

출력 :

{'name': 'First Last', 'comment': 'id_192743918', 'email': '[email protected]'} 
1

또 다른 해결책 :

line = 'First Last (id_192743918) <[email protected]>' 

l = line.split() 

result = {'name': l[0]+' '+l[1], 'comment':l[2][1:-1], 'email':l[3][1:-1]} 
1

는 그냥 다른 다시 예 : 나는 모든 해답을 좋아하지만,이 하나의 분명한입니다

text='First Last (id_192743918) <[email protected]>' 

matches=re.findall("(^.*)\((.*)\).*<(.*)>", text)[0] 

result={"name":matches[0].strip(), 
     "comment":matches[1].strip(), 
     "email":matches[2].strip()} 
관련 문제