我已经编写了这个程序,它将接受一个用户句子,用它们的位置替换用户句子中的单词并显示新句子。 然而,当我运行它时,程序运行良好,但如果句子包含超过 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
有人可以帮我解决这个问题吗?
最佳答案
我觉得你想多了。
如果您想要唯一值(顺序无关紧要),请使用 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)
关于python - 输出间距错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42934126/