输出间距错误

Output spacing error

我编写了这个程序,它将接受一个用户句子,用它们的位置替换用户句子中的单词并显示新句子。 然而,当我 运行 它程序运行正常,但如果句子包含超过 9 个不同的单词,则包含更多数字的位置将单独显示。这是代码:

UserSentence = input("Please enter sentence: \n")
UniqueWords = []
NewSentence = "" 

splitsentence = UserSentence 
splitsentence = splitsentence.lower().split() 

for word in splitsentence: 
    if word not in UniqueWords: 
        UniqueWords.append(word) 

for word in splitsentence:
    NewSentence += str(UniqueWords.index(word)+1) 

NewSentence = ' '.join(NewSentence) 
print (NewSentence)

如果我输入这句话: "this sentence contains more than ten words but the output is wrong i do not know what to say" 预期输出应为:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

但是我把所有的数字都放在一起,即使两位数的数字被 space:

分隔
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9

有人可以帮我解决这个问题吗?

当您的句子如下所示时,您正在调用 ' '.join(NewSentence)1234...111213 因此 join()NewSentence 拆分为各个字符。您应该在每个循环后将 space 添加到 NewSentence,而不是调用 join()。这应该是你想要的:

UserSentence = input("Please enter sentence: \n")
UniqueWords = []
NewSentence = ""

splitsentence = UserSentence
splitsentence = splitsentence.lower().split()

for word in splitsentence:
    if word not in UniqueWords:
        UniqueWords.append(word)

for word in splitsentence:
    NewSentence += str(UniqueWords.index(word)+1) + " "

print(NewSentence)

我觉得你想多了。

如果您想要唯一值(顺序无关紧要),请使用 set()

sentence = input("Please enter sentence: \n")
words = sentence.lower().split() 
unique_words = set(words)

那么,您只是想要一个数字列表?单词本身并不重要,重要的是该集合的大小。

new_sentence = range(1, len(unique_words)+1)

print(' '.join(map(str, new_sentence)))

输出

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

如果顺序和单词确实重要,则继续使用列表,但您可以更简洁地完成最终输出

new_sentence = [ str(unique_words.index(word)+1) for word in unique_words ]
new_sentence = ' '.join(new_sentence)

第 13 行出错:

NewSentence += str(UniqueWords.index(word)+1) 

您应该添加一个间隔符,完成后您的代码应该如下所示:

UserSentence = raw_input("Please enter sentence: \n")
UniqueWords = []
NewSentence = "" 

splitsentence = UserSentence 
splitsentence = splitsentence.lower().split() 

for word in splitsentence: 
    if word not in UniqueWords: 
        UniqueWords.append(word) 

for word in splitsentence:
    NewSentence += str(UniqueWords.index(word)+1)+" "

print NewSentence

正如其他答案所暗示的那样,您过于复杂了。您需要打印出一个字符串,其中包含一组由 space 分隔的递增数字,句子中的每个单词一个数字。

首先,获取句子的单词长度:

length = len(UserSentence.split())

然后,在该范围内构造一个字符串:

newSentence = ' '.join([str(i+1) for i in range(length)])

join 方法的参数是一个列表理解;它允许您在一行中构建列表)

然后打印出来:

print(newSentence)