输出间距错误

时间:2017-03-21 17:22:07

标签: python output space

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

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

4 个答案:

答案 0 :(得分:3)

我认为你过分思考这个问题。

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

答案 1 :(得分:1)

当您的句子如下所示时,您正在呼叫' '.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)

答案 2 :(得分:1)

第13行出错:

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

你应该添加一个spacer,完成后你的代码应该是这样的:

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

答案 3 :(得分:1)

与其他答案一样,你过于复杂。您需要打印出一个字符串,其中包含一组用空格分隔的增量数字,句子中每个单词都有一个数字。

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

length = len(UserSentence.split())

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

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

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

然后,打印出来:

print(newSentence)
相关问题