-1

I am wondering how to convert words from an input into values in Python. The user would enter an input for example:

"The dog chased the cat the lion chased the dog"

I would then like it to return:

["1,2,3,1,4,1,5,6,1,2"]

I would like duplicate words to retain the same value as when the word first occurred. I have tried to do this multiple ways, I am using the following code at the moment, but it seems to return random indexes:

l = input("Enter a sentence").lower lists= list(l) valueindex = range(len(lists)) print(valueindex)

Thanks for the help, Izaak

I.Hull
  • 11
  • 5

1 Answers1

-1
def text_process(text):
    '''split text to list and all the item are lower case'''

    text_list = text.lower().split()
    return text_list

def lookup_table(text_list):
    '''build dict contain the text and number pair'''

    lookup = {}
    start = 0
    for item in text_list:
        if item not in lookup:
            lookup[item] = start + 1
            start += 1
    return lookup

if __name__ == '__main__':
    text = "The dog chased the cat the lion chased the dog"
    text_list = text_process(text)
    lookup_table = lookup_table(text_list)
    out_put = [lookup_table[text]for text in text_list]
    print(out_put)

out:

[1, 2, 3, 1, 4, 1, 5, 3, 1, 2]
宏杰李
  • 11,820
  • 2
  • 28
  • 35