Domanda

Ho un file con linee come

account = "TEST1" Qty=100 price = 20.11 subject="some value" values="3=this, 4=that"

Non esiste un delimitatore speciale e ogni chiave ha un valore racchiuso tra virgolette doppie se è una stringa ma non se è un numero. Non esiste una chiave senza un valore sebbene possano esistere stringhe vuote che sono rappresentate come " " e non esiste un carattere di escape per una citazione in quanto non è necessario

Voglio sapere qual è un buon modo per analizzare questo tipo di linea con Python e memorizzare i valori come coppie chiave-valore in un dizionario

È stato utile?

Soluzione

Avremo bisogno di una regex per questo.

import re, decimal
r= re.compile('([^ =]+) *= *("[^"]*"|[^ ]*)')

d= {}
for k, v in r.findall(line):
    if v[:1]=='"':
        d[k]= v[1:-1]
    else:
        d[k]= decimal.Decimal(v)

>>> d
{'account': 'TEST1', 'subject': 'some value', 'values': '3=this, 4=that', 'price': Decimal('20.11'), 'Qty': Decimal('100.0')}

Se preferisci, puoi usare float anziché decimale, ma probabilmente è una cattiva idea se è coinvolto denaro.

Altri suggerimenti

Forse un po 'più semplice da seguire è la pyparsing resa:

from pyparsing import *

# define basic elements - use re's for numerics, faster than easier than 
# composing from pyparsing objects
integer = Regex(r'[+-]?\d+')
real = Regex(r'[+-]?\d+\.\d*')
ident = Word(alphanums)
value = real | integer | quotedString.setParseAction(removeQuotes)

# define a key-value pair, and a configline as one or more of these
# wrap configline in a Dict so that results are accessible by given keys
kvpair = Group(ident + Suppress('=') + value)
configline = Dict(OneOrMore(kvpair))

src = 'account = "TEST1" Qty=100 price = 20.11 subject="some value" ' \
        'values="3=this, 4=that"'

configitems = configline.parseString(src)

Ora puoi accedere ai tuoi pezzi usando l'oggetto ParseResults configitems restituito:

>>> print configitems.asList()
[['account', 'TEST1'], ['Qty', '100'], ['price', '20.11'], 
 ['subject', 'some value'], ['values', '3=this, 4=that']]

>>> print configitems.asDict()
{'account': 'TEST1', 'Qty': '100', 'values': '3=this, 4=that', 
  'price': '20.11', 'subject': 'some value'}

>>> print configitems.dump()
[['account', 'TEST1'], ['Qty', '100'], ['price', '20.11'], 
 ['subject', 'some value'], ['values', '3=this, 4=that']]
- Qty: 100
- account: TEST1
- price: 20.11
- subject: some value
- values: 3=this, 4=that

>>> print configitems.keys()
['account', 'subject', 'values', 'price', 'Qty']

>>> print configitems.subject
some value

Una variazione ricorsiva dei valori di analisi di bobince con incorporati equivale a dizionari:

>>> import re
>>> import pprint
>>>
>>> def parse_line(line):
...     d = {}
...     a = re.compile(r'\s*(\w+)\s*=\s*("[^"]*"|[^ ,]*),?')
...     float_re = re.compile(r'^\d.+)
...     int_re = re.compile(r'^\d+)
...     for k,v in a.findall(line):
...             if int_re.match(k):
...                     k = int(k)
...             if v[-1] == '"':
...                     v = v[1:-1]
...             if '=' in v:
...                     d[k] = parse_line(v)
...             elif int_re.match(v):
...                     d[k] = int(v)
...             elif float_re.match(v):
...                     d[k] = float(v)
...             else:
...                     d[k] = v
...     return d
...
>>> line = 'account = "TEST1" Qty=100 price = 20.11 subject="some value" values=
"3=this, 4=that"'
>>> pprint.pprint(parse_line(line))
{'Qty': 100,
 'account': 'TEST1',
 'price': 20.109999999999999,
 'subject': 'some value',
 'values': {3: 'this', 4: 'that'}}

Se non vuoi usare una regex, un'altra opzione è solo quella di leggere la stringa un carattere alla volta:

string = 'account = "TEST1" Qty=100 price = 20.11 subject="some value" values="3=this, 4=that"'

inside_quotes = False
key = None
value = ""
dict = {}

for c in string:
    if c == '"':
        inside_quotes = not inside_quotes
    elif c == '=' and not inside_quotes:
        key = value
        value = ''
    elif c == ' ':
        if inside_quotes:
            value += ' ';
        elif key and value:
            dict[key] = value
            key = None
            value = ''
    else:
        value += c

dict[key] = value
print dict
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top