Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Like this? Just do a list-comprehension to get all the indices of all the words.

In [77]: sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"

In [78]: words = sentence.split()

In [79]: [words.index(s)+1 for s in words]
Out[79]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 9, 6, 7, 8, 4, 5]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...