Mapping and Filtering Help for Lists
Arnaud Delobelle
arnodel at googlemail.com
Sun Apr 27 13:22:23 EDT 2008
Zethex <zethex at hotmail.com> writes:
> Alright I got asked today by a friend this question, which obviously I
> couldn't help him with.
>
> He needs to get rid of words in a string referring to an already given list
> then needs to map them using a function he already has. Ill explain this
> better by giving an example :P
>
> Say ur given these lists:
>
> un_words = ['a', 'the', 'he', 'she', 'uses', 'with']
> alterns = [ ['book', 'textbook', 'notepad'], ['pencil', 'pen', 'pacer'] ]
>
> The problem asks to create a "compareandremove" so that you can use it on a
> string, to remove the words from the string that are contained in un_words.
>
> The remaining words then need to be compared to the alterns list and either
> bring back the word if no matches or bring back the list. To better explain
> that i'll use an example.
>
> If i do compareandremove('notepad a pencil with desk')
>
> I need it so it removes words contained in un_words, so "a" and "with";
> then compares the remaining words to alterns to find a match.
>
> This should bring back:
>
> ['notepad', 'book', 'textbook', 'pencil', 'pen', 'pacer', 'desk']
>
>
> Any tips on how to create this function or maybe the function itself so I
> can then show him how to do it.
>
> Thank you.
Look away now if you don't want a complete solution!
un_words = ['a', 'the', 'he', 'she', 'uses', 'with']
alterns = [ ['book', 'textbook', 'notepad'], ['pencil', 'pen', 'pacer'] ]
# these words will be replaced with nothing
wordmap = dict((w, []) for w in un_words)
# these words will be replaced with the list of their synonyms
for wordlist in alterns:
for word in wordlist:
wordmap[word] = wordlist
def compareandremove(sentence):
return [x for w in sentence.split() for x in wordmap.get(w, [w])]
# Example
>>> compareandremove('notepad a pencil with desk')
['book', 'textbook', 'notepad', 'pencil', 'pen', 'pacer', 'desk']
--
Arnaud
More information about the Python-list
mailing list