在句子中写一个数字

时间:2016-12-03 23:27:01

标签: python python-3.x

我正在尝试用数字替换单词来打印句子。例如,“这是一个测试,这是一个测试”将成为“1234 1234”。

这是我到目前为止所做的:

sentence_list = []
sentence = input('Input a sentence \n')
sentence_list.append(sentence)
print(sentence_list)
numbers = [val + '=' + str(i + 1) for i, val in enumerate(sentence.split())]
print(numbers)

但是,我不知道怎么去说明重复的单词,而且只打印数字而不是“[word = 1]”

3 个答案:

答案 0 :(得分:0)

与Max相同,只是更简单一点。

SentenceList=[]
sentence=input('Input a sentence \n')

sentenceSplit = sentence.split(' ')

for word in sentenceSplit:
    if word not in SentenceList:
        SentenceList.append(word)
    print SentenceList.index(word) + 1,

答案 1 :(得分:0)

words_found = [] 

for word in input('Input a sentence \n').split():
    # Add each word to the list the first time it appears
    if word not in words_found:
        words_found.append(word)
    # Print the index in the last that the word appeared in
    print(words_found.index(word) + 1)

答案 2 :(得分:0)

Max's solution很棒,因为它使用字典进行O(1)查找。可以使它变得更加简单

data = {}

for word in input('Input a sentence \n').split():
    if word not in data:
        data[word] = len(data) + 1
    print(data[word])

或使用dict.setdefault

data = {}

for word in input('Input a sentence \n').split():
    print(data.setdefault(word, len(data) + 1))