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

4

3 に答える 3

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

識別子を使用して属性を検索する場合は、辞書を使用できます。

于 2013-06-10T22:27:47.677 に答える
0

正規表現の使用:

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(',')

識別子にペアがあることがすでにわかっている場合は、make,yearそれらも抽出できます。

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.
于 2013-06-10T22:07:32.950 に答える