特定の識別子の前にある場合、文字列から部分文字列を抽出する方法を探しています。
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 を考慮しなかった理由の 1 つは、キーが一意である必要があり、複数行のテキストがあり、同じ行に newCar エントリが重複している可能性があるためです。また、括弧内のテキストは、make = Toyota/Ford または year = 2010/2013 を示す可能性があるため、一般的な用語にすぎません。