输出间距错误

问题描述:

我已经编写了这个程序,它将接受用户句子,用它们的位置替换用户句子中的单词并显示新句子。 但是,当我运行它的程序工作正常,但如果句子包含超过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) 

,如果我进入了这样一句话: “这句话包含了超过十个字,但输出是错误的,我不知道该说什么” 预期结果应该是:

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

而是我得到的所有数字都在一起,甚至两位数的数字之间用空格分隔:

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 

能有人帮助我牛逼o解决这个问题?

+0

在调用join()之前尝试'print(NewSentence)'。 –

+0

我已经尝试过,但我仍然得到输出,但像这样聚集12345678910111213141516171819 –

+0

使NewSentence成为'list'并追加到它'NewSentence.append(str(UniqueWords.index(word)+1)' – davedwards

当您的语句如下所示时,您正在调用' '.join(NewSentence)1234...111213因此join()NewSentence拆分为其各个字符。您应该在每个循环后为空间添加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) 
+0

希望你不要但是,这与我的回答是一致的......但无论如何,我都赞成了 – Veltro

+0

@Liam你在我做完之后提交了答案:||。顺便说一句,谢谢+1 –

+0

@downvoters ....总是陈述你为什么downvote –

我想你是在思考问题。

如果您想要唯一值(订单无关紧要),请使用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 
+1

希望你不要介意,但这与我的回答相同...... –

像其他答案建议,你是过于复杂。您需要输出一个字符串,其中包含一个由空格分隔的增量数字,每个单词在句子中都有一个数字。

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

length = len(UserSentence.split()) 

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

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

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

然后,打印它:

print(newSentence) 
+1

+1对于给定任务非常好的方法。我想以完全相同的方式完成,但我想说明OP正在处理的问题 –