Faker Faker - 6 months ago 282
Python Question

Individual words in a list then printing the positions of those words

I need help with a program that identifies individual words in a sentence, stores these in a list and replaces each word in the original sentence with the position of that word in the list. Here is what I have so far.

for example:

'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR' COUNTRY


would recreated as 1,2,3,4,5,6,7,8,9,1,3,9,6,7,8,4,5

from collections import OrderedDict

sentence = input("Please input a sentence without punctuation").upper()

punctuation = ("`1234567890-=¬!£$%^&*()_+\|[];'#,./{}:@~<>?")

FilteredSentence = ("")

for char in sentence:
if char not in punctuation:
FilteredSentence = FilteredSentence+char

FilteredSentence = FilteredSentence.split(" ")

refined = list(OrderedDict.fromkeys(FilteredSentence))


I have managed to identify the individual words in the list however I work out how to replace the words in the original list with the positions of the individual words.

Answer

You can also create a dictionary mapping the words with their initial position, then use it to substitute the words with their respective positions.

>>> s = 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY'
>>> 
>>> 
>>> l = s.split()
>>> l
['ASK', 'NOT', 'WHAT', 'YOUR', 'COUNTRY', 'CAN', 'DO', 'FOR', 'YOU', 'ASK', 'WHAT', 'YOU', 'CAN', 'DO', 'FOR', 'YOUR', 'COUNTRY']
>>> 
>>> d = dict((s, l.index(s)+1) for s in set(l))
>>> d
{'DO': 7, 'COUNTRY': 5, 'CAN': 6, 'WHAT': 3, 'ASK': 1, 'YOUR': 4, 'NOT': 2, 'FOR': 8, 'YOU': 9}
>>> list(map(lambda s: d[s], l))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 9, 6, 7, 8, 4, 5]
>>>