simple question on list manipulation from a newbie

Larry Bates larry.bates at websafe.com`
Sat Jun 7 16:06:39 EDT 2008


Sengly wrote:
> Dear all,
> 
> I am working with wordnet and I am a python newbie. I'd like to know
> how can I transfer a list below
> 
> In [69]: dog
> Out[69]:
> [{noun: dog, domestic_dog, Canis_familiaris},
>  {noun: frump, dog},
>  {noun: dog},
>  {noun: cad, bounder, blackguard, dog, hound, heel},
>  {noun: frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst,
> weenie},
>  {noun: pawl, detent, click, dog},
>  {noun: andiron, firedog, dog, dog-iron}]
> 
> to a list like this with python:
> 
> [dog, domestic_dog, Canis_familiaris,
> frump, dog,
> dog,
> cad, bounder, blackguard, dog, hound, heel,
> frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst,
> weenie},
> pawl, detent, click, dog},
> andiron, firedog, dog, dog-iron]
> 
> Thank you.
> 
> Sengly
> 

You should at least tell us what you have tried and where this information is 
coming from and in what format.

Assumptions:

1) is a string containing what is shown (not a list of dictionaries)
2) the result you want is also a string (not a list)

out = '[{noun: dog, domestic_dog, Canis_familiaris},{noun: frump, dog},' \
       '{noun: dog},{noun: cad, bounder, blackguard, dog, hound, heel},' \
       '{noun: frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst, ' \
       'weenie}, {noun: pawl, detent, click, dog}, {noun: andiron, firedog, ' \
       'dog, dog-iron}]'

l = out.replace('}', '')[1:-1].split('{noun: ')[1:]

results = []
for entry in l:
     words = [x.strip() for x in entry.split(',')]
     results.extend(words)

print results


Note: this is very specific to the contents you show.  If you need a general 
solution you will either need to use regexes or look a pyparsing.

-Larry



More information about the Python-list mailing list