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

2024-09-29 02:20:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

这是我尝试过的,但我似乎只得到了第一次出现的(…)。有什么办法来解决这个问题,如果我能把单个的字符串也放在括号里会更好吗?在

^{pr2}$

编辑: 谢谢你的回复。我没有考虑Dict的一个原因是键必须是唯一的,而且我有一个多行的文本,在同一行中可能有重复的newCar条目。括号内的文字只是通用术语,因为它可能表示make=Toyota/Ford或year=2010/2013。在


Tags: or方法字符串makeattribute标识符year括号
3条回答

这肯定不是最好的解决办法,但它是有效的。在

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

使用正则表达式:

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对,您也可以提取它们:

^{pr2}$
params = sent.split(id1)[1].split(")")[0].lstrip("(")
print params

你想怎么做就怎么做。尽管如此,还是有更好的方法来做到这一点。您可以将项目存储为键:值对例如使用字典。在

相关问题 更多 >