简体   繁体   English

如何从Python(旧版)格式字符串中提取字段名称?

[英]How can I extract the field names from a Python (legacy) format string?

I'm finding this to be a difficult question to put into words, hence the examples. 我发现这是一个难以理解的问题,因此就是例子。 However, I'm basically being given arbitrary format strings , and I need to go (efficiently) fetch the appropriate values from a database, in order to build a relevant mapping object dynamically. 但是,我基本上被赋予任意格式字符串 ,并且我需要(有效地)从数据库中获取适当的值,以便动态地构建相关的映射对象。

Given a format string expecting a mapping object, eg: 给定期望映射对象的格式字符串,例如:

>>> 'Hello, %(first-name)s!' % {'first-name': 'Dolph'}
'Hello, Dolph!'

I'm looking for an implementation of 'infer_field_names()' below: 我正在寻找下面的'infer_field_names()'的实现:

>>> infer_field_names('Hello, %(first-name)s! You are #%(customer-number)d.')
['first-name', 'customer-number']

I know I could write regex (or even try to parse exception messages!), but I'm hoping there's an existing API call I can use instead..? 我知道我可以编写正则表达式(甚至尝试解析异常消息!),但我希望有一个我可以使用的现有API调用..?

Based on the string Formatter docs , I thought this would work: 基于字符串Formatter docs ,我认为这样可行:

>>> import string
>>> format_string = 'Hello, %(first-name)s! You are #%(customer-number)d.'
>>> [x[1] for x in string.Formatter().parse(format_string)]
[None]

But that doesn't quite return what I would expect (a list of field_name s, per the docs). 但这并没有完全回归我所期望的(每个文档的field_name s列表)。

When using the % operator to format strings, the right operand doesn't have to be a dictionary -- it only has to be some object mapping the required field names to the values that are supposed to be substistuted. 使用%运算符格式化字符串时,右操作数不必是字典 - 它只需要是一些对象,将所需的字段名称映射到应该被替换的值。 So all you need to do is write a class with an redefined __getitem__() that retrieves the values from the database. 所以你需要做的就是编写一个带有重新定义的__getitem__()的类,它从数据库中检索值。

Here's a pointless example: 这是一个毫无意义的例子:

class Mapper(object):
    def __getitem__(self, item):
        return item   

print 'Hello, %(first-name)s!' % Mapper()

prints 版画

Hello, first-name!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM