我想知道如何将输入中的单词转换为Python中的值。用户可以输入输入,例如:
"The dog chased the cat the lion chased the dog"
我希望它返回:
["1,2,3,1,4,1,5,6,1,2"]
我希望重复的单词保留与单词首次出现时相同的值。我试过多种方式,我现在使用下面的代码,但它似乎返回随机索引:
l = input("Enter a sentence").lower lists= list(l) valueindex = range(len(lists)) print(valueindex)
感谢您的帮助, 艾萨克
答案 0 :(得分:-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)
出:
[1, 2, 3, 1, 4, 1, 5, 3, 1, 2]