繁体   English   中英

反向使用Python格式字符串进行解析

[英]Use Python format string in reverse for parsing

我一直在使用以下python代码将整数部件ID格式化为格式化的部件号字符串:

pn = 'PN-{:0>9}'.format(id)

我想知道是否有一种方法可以反向使用相同的格式字符串( 'PN-{:0>9}' )来从格式化的部件号中提取整数ID。 如果无法做到,有没有办法使用单个格式字符串(或正则表达式?)来创建和解析?

解析模块 “与format()”相反。

用法示例:

>>> import parse
>>> format_string = 'PN-{:0>9}'
>>> id = 123
>>> pn = format_string.format(id)
>>> pn
'PN-000000123'
>>> parsed = parse.parse(format_string, pn)
>>> parsed
<Result ('123',) {}>
>>> parsed[0]
'123'

你可能会发现模拟scanf interresting。

怎么样:

id = int(pn.split('-')[1])

这将拆分破折号处的零件号,获取第二个组件并将其转换为整数。

PS我保留id作为变量名称,以便与您的问题的连接清晰。 重命名该变量不会影响内置函数是个好主意。

如果您不想使用解析模块,这是一个解决方案。 它将格式字符串转换为具有命名组的正则表达式。 它做了一些假设(在docstring中描述)在我的情况下是可以的,但在你的情况下可能不合适。

def match_format_string(format_str, s):
    """Match s against the given format string, return dict of matches.

    We assume all of the arguments in format string are named keyword arguments (i.e. no {} or
    {:0.2f}). We also assume that all chars are allowed in each keyword argument, so separators
    need to be present which aren't present in the keyword arguments (i.e. '{one}{two}' won't work
    reliably as a format string but '{one}-{two}' will if the hyphen isn't used in {one} or {two}).

    We raise if the format string does not match s.

    Example:
    fs = '{test}-{flight}-{go}'
    s = fs.format('first', 'second', 'third')
    match_format_string(fs, s) -> {'test': 'first', 'flight': 'second', 'go': 'third'}
    """

    # First split on any keyword arguments, note that the names of keyword arguments will be in the
    # 1st, 3rd, ... positions in this list
    tokens = re.split(r'\{(.*?)\}', format_str)
    keywords = tokens[1::2]

    # Now replace keyword arguments with named groups matching them. We also escape between keyword
    # arguments so we support meta-characters there. Re-join tokens to form our regexp pattern
    tokens[1::2] = map(u'(?P<{}>.*)'.format, keywords)
    tokens[0::2] = map(re.escape, tokens[0::2])
    pattern = ''.join(tokens)

    # Use our pattern to match the given string, raise if it doesn't match
    matches = re.match(pattern, s)
    if not matches:
        raise Exception("Format string did not match")

    # Return a dict with all of our keywords and their values
    return {x: matches.group(x) for x in keywords}

暂无
暂无

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

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