1

非常に大きなカスタムメイドの設定ファイルがあり、週に1回データを抽出する必要があります。これは「社内」の構成ファイルであり、INIなどの既知の標準に準拠していません。

私の手っ取り早いアプローチは、reを使用して必要なセクションヘッダーを検索し、このヘッダーの下にある1行または2行の情報を抽出することでした。これはかなりの挑戦であり、これを行うためのより簡単で信頼性の高い方法があるはずだと思いますが、このファイルを解析し、5行を抽出するために完全なパーサーを実装する必要があると私は考え続けています必要なデータ。

「セクション」は次のようになります。

Registry com.name.version =
Registry "unique-name I search for using re" =
    String name = "modulename";
    String timestamp = "not specified";
    String java = "not specified";
    String user = "not specified";
    String host = "not specified";
    String system = "not specified";
    String version = "This I want";
    String "version-major" = "not specified";
    String "version-minor" = "not specified";
    String scm = "not specified";
    String scmrevision = "not specified";
    String mode = "release";
    String teamCityBuildNumber = "not specified";
;
4

4 に答える 4

2

pyparsingを使用する単純なパーサーは、デシリアライザーに近いものを提供できます。これにより、キー名(dictなど)または属性としてフィールドにアクセスできます。これがパーサーです:

from pyparsing import (Suppress,quotedString,removeQuotes,Word,alphas,
        alphanums, printables,delimitedList,Group,Dict,ZeroOrMore,OneOrMore)

# define punctuation and constants - suppress from parsed output
EQ,SEMI = map(Suppress,"=;")
REGISTRY = Suppress("Registry")
STRING = Suppress("String")

# define some basic building blocks
quotedString.setParseAction(removeQuotes)
ident = quotedString | Word(printables)
value = quotedString
java_path = delimitedList(Word(alphas,alphanums+"_"), '.', combine=True)

# define the config file sections
string_defn = Group(STRING + ident + EQ + value + SEMI)
registry_section = Group(REGISTRY + ident + EQ + Dict(ZeroOrMore(string_defn)))

# special definition for leading java module
java_module = REGISTRY + java_path("path") + EQ

# define the overall config file format
config = java_module("java") + Dict(OneOrMore(registry_section))

データを使用したテストは次のとおりです(データファイルからconfig_sourceに読み込まれます)。

data = config.parseString(config_source)
print data.dump()
print data["unique-name I search for using re"].version
print data["unique-name I search for using re"].mode
print data["unique-name I search for using re"]["version-major"]

プリント:

['com.name.version', ['unique-name I search for using re', ...
- java: ['com.name.version']
  - path: com.name.version
- path: com.name.version
- unique-name I search for using re: [['name', 'modulename'], ...
  - host: not specified
  - java: not specified
  - mode: release
  - name: modulename
  - scm: not specified
  - scmrevision: not specified
  - system: not specified
  - teamCityBuildNumber: not specified
  - timestamp: not specified
  - user: not specified
  - version: This I want
  - version-major: not specified
  - version-minor: not specified
This I want
release
not specified
于 2010-02-23T16:05:36.280 に答える
1

特別なコンテンツのみを探す場合は、正規表現を使用しても問題ありません。すべてを読む必要がある場合は、パーサーを自分で作成する必要があります。

>> s = ''' ... ''' # as above
>> t = re.search( 'Registry "unique-name" =(.*?)\n;', s, re.S ).group( 1 )
>> u = re.findall( '^\s*(\w+) "?(.*?)"? = "(.*?)";\s*$', t, re.M )
>> for x in u:
       print( x )

('String', 'name', 'modulename')
('String', 'timestamp', 'not specified')
('String', 'java', 'not specified')
('String', 'user', 'not specified')
('String', 'host', 'not specified')
('String', 'system', 'not specified')
('String', 'version', 'This I want')
('String', 'version-major', 'not specified')
('String', 'version-minor', 'not specified')
('String', 'scm', 'not specified')
('String', 'scmrevision', 'not specified')
('String', 'mode', 'release')

編集:上記のバージョンは複数のレジストリセクションで機能するはずですが、より厳密なバージョンは次のとおりです。

t = re.search( 'Registry "unique-name"\s*=\s*((?:\s*\w+ "?[^"=]+"?\s*=\s*"[^"]*?";\s*)+)\s*;', s ).group( 1 )
u = re.findall( '^\s*(\w+) "?([^"=]+)"?\s*=\s*"([^"]*?)";\s*$', t, re.M )
于 2010-02-23T10:02:55.100 に答える
0

キーの辞書を使用してセクションの辞書を作成する単純なパーサーを作成する必要があると思います。何かのようなもの:

#!/usr/bin/python

import re

re_section = re.compile('Registry (.*)=', re.IGNORECASE)
re_value = re.compile('\s+String\s+(\S+)\s*=\s*(.*);')

txt = '''
Registry com.name.version =
Registry "unique-name I search for using re" =
        String name = "modulename";
        String timestamp = "not specified";
        String java = "not specified";
        String user = "not specified";
        String host = "not specified";
        String system = "not specified";
        String version = "This I want";
        String "version-major" = "not specified";
        String "version-minor" = "not specified";
        String scm = "not specified";
        String scmrevision = "not specified";
        String mode = "release";
        String teamCityBuildNumber = "not specified";
'''

my_config = {}
section = ''
lines = txt.split('\n')
for l in lines:
    rx = re_section.search(l)
    if rx:
        section = rx.group(1)
        section = section.strip('" ')
        continue
    rx = re_value.search(l)
    if rx:
        (k, v) = (rx.group(1).strip('" '), rx.group(2).strip('" '))
        try:
            my_config[section][k] = v
        except KeyError:
            my_config[section] = {k: v}

次に、次の場合:

print my_config["unique-name I search for using re"]['version']

次のように出力されます。

This I want
于 2010-02-23T10:12:52.990 に答える
0

正規表現には状態がないため、これらを使用して複雑な入力を解析することはできません。ただし、ファイルを文字列にロードし、正規表現を使用してサブ文字列を見つけ、その場所で文字列を切り取ることができます。

あなたの場合は、を検索しr'unique-name I search for using re"\s*=\s*'、一致後にカットします。次に、一致する前に検索しr'\n\s*;\s*\n'てカットします。これにより、別の正規表現を使用して切り刻むことができる値が残ります。

于 2010-02-23T09:49:09.173 に答える