Home > Software design >  Read a textfile name(category) into different category dictionaries in python?
Read a textfile name(category) into different category dictionaries in python?

Time:09-17

I have a textfile that looks like this

radiant(a) vibe(n) pen(n) lightly(d) stares(v) bright(a) dust(n) graceful(a) dazzling(a) abruptly(d)
running(a) cheerfully(d) wriggles(v) inkwell(n) sky(n) running(a) divine(a) tear(n) rappidly(d)

I need python to read into this textfile and return me an overview of dictionaries like this:

{'a': ['radiant', 'bright', 'graceful', ...],
 'n': ['vibe', 'pen', 'dust', ...],
 'd': ['lightly', 'abruptly', 'cheerfully',...],
 'v': ['stares', 'wriggles', 'smiles',...]}

Can anyone maybe help me? Thanks :)

CodePudding user response:

Try this:

from collections import defaultdict

st = 'radiant(a) vibe(n) pen(n) lightly(d) stares(v) bright(a) dust(n) graceful(a) dazzling(a) abruptly(d) running(a) cheerfully(d) wriggles(v) inkwell(n) sky(n) running(a) divine(a) tear(n) rappidly(d)'

d = defaultdict(list)

for i in st.split():
    d[i[-2]].append(i[:-3])

Output:

>>> print(d)
defaultdict(<class 'list'>, {
'a': ['radiant', 'bright', 'graceful', 'dazzling', 'running', 'running', 'divine'], 
'n': ['vibe', 'pen', 'dust', 'inkwell', 'sky', 'tear'], 
'd': ['lightly', 'abruptly', 'cheerfully', 'rappidly'], 
'v': ['stares', 'wriggles']
})

CodePudding user response:

Try itertools.groupby:

from itertools import groupby
{k[1:-1]: [x[:-3] for x in v] for k, v in groupby(sorted(st.split(), key=lambda x: x[-3:]), key=lambda x: x[-3:])}

Or dict.setdefault for efficiency:

dct = {}
for x in st.split():
    dct.setdefault(x[-2:-1], []).append(x[:-3])
print(dct)

Both codes output:

{'a': ['radiant', 'bright', 'graceful', 'dazzling', 'running', 'running', 'divine'], 'n': ['vibe', 'pen', 'dust', 'inkwell', 'sky', 'tear'], 'd': ['lightly', 'abruptly', 'cheerfully', 'rappidly'], 'v': ['stares', 'wriggles']}
  • Related