2013-06-10 3 views
0

특정 식별자 앞에 문자열이 있으면 문자열에서 부분 문자열을 추출 할 방법을 찾고 있습니다.문자열에서 괄호 안에있는 부분 문자열을 추출하는 파이썬

string = [food(type, description), newCar(make, year), fruit(shape, colour), usedCar(make, year), ..., identifier(str1, str2)] 
identifier = car (newCar and/or usedCar) - extract if both appear or either one appear 

Desired outcome 

identifier: newCar 
first attribute = make 
second attribue = year 

identifier: usedCar 
first attribute = make 
second attribue = year 

이것은 내가 시도한 것이지만 나는 (..)의 첫 번째 항목 만 얻는 것처럼 보입니다. 이 문제를 해결할 수있는 아이디어가 있다면 브래킷 안에 개별 문자열을 넣을 수도 있습니다.

sent = '[food(type, description, newCar(make, year), fruit(shape, colour), usedCar(make, year), ..., identifier(str1, str2)]' 

id1 = 'newCar' 
id2 = 'usedCar' 

if id1 in sent: 
    carDesc1= sent.split("(")[1].split(")")[0] 
    print carDesc1 

    if id2 in sent: 
     carDesc2= sent.split("(")[1].split(")")[0] 
     print carDesc2 

Print results: 
type, description 
type, description 

편집 : 감사합니다. Dict를 고려하지 않은 이유 중 하나는 키가 고유해야하며 여러 줄이있는 텍스트가 있고 같은 줄에 중복 된 newCar 항목이있을 수 있기 때문입니다. 그리고 괄호 안에있는 텍스트는 make = Toyota/Ford 또는 year = 2010/2013을 나타낼 수있는 일반적인 용어 일뿐입니다.

답변

0
params = sent.split(id1)[1].split(")")[0].lstrip("(") 
print params 

원하는대로해야합니다. 그것은 말하기를, 이것을하는 더 좋은 방법이 있습니다. 예를 들어 사전을 사용하여 키 : 값 쌍으로 항목을 저장할 수 있습니다.

import re 

escaped_identifiers = [re.escape(id) for id in ('newCar', 'usedCar')] 
regex = re.compile(r'({})\(([^,]*),([^)]*)\)'.format('|'.join(escaped_identifiers))) 
for type, make, year in regex.findall(the_text): 
    # process a match. 
0

정규 표현식을 사용하여.

string = '[food(type, description), newCar(make, year), fruit(shape, colour), usedCar(make, year)]' 
# Strip the brackets from the string 
string = string.strip('[]') 

# Create a dict with identifiers and attributes 
id_attr = dict([i.split('(') for i in string.split('), ')]) 

# Clean up the attributes and make a list of them 
for identifier, attributes in id_attr.items(): 
    id_attr[identifier] = attributes.strip(')').split(', ') 

for i, attrs in id_attr.items(): 
    # Print the identifier 
    print('identifier: {i}'.format(i=i)) 
    # Print each attribute, numbered 
    for num, a in enumerate(attrs): 
     print('attribute {num}: {a}'.format(num=num, a=a)) 
    print('') # Print empty line 

식별자를 사용하여 속성을 조회하려면 dict를 사용할 수 있습니다.

0

그것은 결정적으로 최선의 해결책은 아니지만 작동 : 이미 식별자가 너무을 추출 할 수있는 make,year 쌍있을 것이라는 점을 알고있는 경우

import re 

escaped_identifiers = [re.escape(id) for id in ('newCar', 'usedCar')] 
regex = re.compile(r'({})\(([^)]*)\)'.format('|'.join(escaped_identifiers))) 
for type, params in regex.findall(the_text): 
    make, year = params.split(',') 

:

관련 문제