Bit of List replacing trouble (newbie)
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Thu May 22 03:44:16 EDT 2008
Zethex a écrit :
> At the moment i'm doing a piece of work for school and I'm stuck at the
> moment.
>
> I have a list of words, for example:
>
> Sentence = ['A', 'dog', 'walked', 'across', 'the', 'street']
<ot>
Naming convention : variable names are all_lower, so s/Sentence/sentence/
</ot>
>
> I have another list which I need to use to replace certain words, and its in
> the form of:
>
> synonyms = [
> [canine, [dog, puppy, bulldog]],
> [ road, [street, avenue, court]]
> ]
NB : I assume this is :
synonyms = [
['canine', ['dog', 'puppy', 'bulldog']],
[ 'road', ['street', 'avenue', 'court']],
]
and FWIW, I'd use a list of tuples, not a list of lists:
synonyms = [
('canine', ['dog', 'puppy', 'bulldog']),
('road', ['street', 'avenue', 'court']),
]
or even better a dict:
synonyms = {
'canine' : ['dog', 'puppy', 'bulldog'],
'road' : ['street', 'avenue', 'court'],
}
> What the procedure must do is replace dog with canine, and street with road.
> Therefore if a word is in the sentence and appears on the right side of the
> list entry, replace it with the left entry.
>
> I can't seem to find a help file with what I'm after.
This is probably not something that you'll find in any 'help file'. As
for almost everything algorithmic, the key is to have the appropriate
data structure. In this case, the appropriate data structure is
obviously a reversed index of the synonyms dict (assuming there is no
duplicate word in the synonyms lists):
reversed_synomyms = dict()
for key, values in synonyms.items():
for word in values:
reversed_synonyms[word] = key
print reversed_synonyms
=> {'court': 'road', 'bulldog': 'canine', 'dog': 'canine', 'street':
'road', 'puppy': 'canine', 'avenue': 'road'}
From then, the replacement procedure is quite obvious:
solution = [reversed_synonyms.get(word, word) for word in sentence]
print solution
=> ['A', 'canine', 'walked', 'across', 'the', 'road']
HTH
More information about the Python-list
mailing list