【问题标题】:Dictionary of ini file dataini文件数据字典
【发布时间】:2015-01-12 14:36:13
【问题描述】:
; commentary
[owner]
name=Justin Case
organization=Chilling Inc.

[database]
; more commentary
server=192.0.0.1
port=123
file=something.csv

[third section]
attribute=value,
that extends to 
the third line,
but not the fourth

给定上面的ini内容,必须构造一个字典,这样

{'owner' : {'name' : 'Justin Case','organization' : 'Chilling Inc.'},
'database' : {'server' : '192.0.0.1', 'port' : '123', 'file' : 'something.csv'},
'third section' : {'attribute' : 'multiline value'}}

我意识到有配置文件解析器,但不允许进行此分配。 目前进展:

with open('ini.txt', encoding='utf8') as data:
    lines = [row for row in data]
    lines_nocom = []
    for row in lines:
        if not row.startswith(';'):
            lines_nocom.append(row)
    dictt = {}

我删除了带有评论的行,因为它们是不必要的。

  1. 如何让 python 识别这些部分及其各自的属性? 即 section1 可以有 2 个属性,而 section2 可以有任意数量的属性 如果我使用[row for row in lines_nocom],那么它如何识别一个部分的结束位置和另一个部分的开始位置?
  2. 如何让python识别多行值?

【问题讨论】:

    标签: python dictionary ini


    【解决方案1】:

    跟踪当前部分并将您的密钥添加到该部分;每次使用方括号找到一行时,都会创建一个新部分。

    对于续行,做类似的事情;跟踪最后使用的名称:

    with open('ini.txt', encoding='utf8') as data:
        section = None  # current section
        name = None     # current name being stored
        result = {}
        for line in data:
            line = line.strip()
    
            if not line or line.startswith(';'):
                # skip comments and empty lines
                continue
    
            if line.startswith('[') and line.endswith(']'):
                # new section
                section_name = line.strip('[]')
                section = result[section_name] = {}
                continue
    
            # add entries to the existing section
            if '=' in line:
                name, _, value = line.partition('=')
                name = name.strip()
                section[name] = value.strip()
            else:
                # adding to last-used name
                section[name] += ' ' + line
    

    演示:

    >>> from io import StringIO
    >>> from pprint import pprint
    >>> sample = StringIO('''\
    ... ; commentary
    ... [owner]
    ... name=Justin Case
    ... organization=Chilling Inc.
    ... 
    ... [database]
    ... ; more commentary
    ... server=192.0.0.1
    ... port=123
    ... file=something.csv
    ... 
    ... [third section]
    ... attribute=value,
    ... that extends to 
    ... the third line,
    ... but not the fourth
    ... ''')
    >>> section = None  # current section
    >>> name = None     # current name being stored
    >>> result = {}
    >>> for line in sample:
    ...     line = line.strip()
    ...     if not line or line.startswith(';'):
    ...         # skip comments and empty lines
    ...         continue
    ...     if line.startswith('[') and line.endswith(']'):
    ...         # new section
    ...         section_name = line.strip('[]')
    ...         section = result[section_name] = {}
    ...         continue
    ...     # add entries to the existing section
    ...     if '=' in line:
    ...         name, _, value = line.partition('=')
    ...         name = name.strip()
    ...         section[name] = value.strip()
    ...     else:
    ...         # adding to last-used name
    ...         section[name] += ' ' + line
    ... 
    >>> pprint(result)
    {'database': {'file': 'something.csv', 'port': '123', 'server': '192.0.0.1'},
     'owner': {'name': 'Justin Case', 'organization': 'Chilling Inc.'},
     'third section': {'attribute': 'value, that extends to the third line, but '
                                    'not the fourth'}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      • 2013-12-30
      • 2013-08-07
      • 2011-03-14
      • 2012-08-09
      • 1970-01-01
      相关资源
      最近更新 更多