Python在字符串中的括号内提取子字符串

时间:2013-06-10 21:40:06

标签: python split string-matching

我正在寻找一种从字符串中提取子字符串的方法,如果它在某个标识符之前。

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。

3 个答案:

答案 0 :(得分:0)

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

那应该做你想要的。话虽如此,有更好的方法来做到这一点。您可以使用字典将项目存储为键:值对。

答案 1 :(得分: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.

答案 2 :(得分: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。