특정 식별자 앞에 문자열이 있으면 문자열에서 부분 문자열을 추출 할 방법을 찾고 있습니다.문자열에서 괄호 안에있는 부분 문자열을 추출하는 파이썬
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을 나타낼 수있는 일반적인 용어 일뿐입니다.