Develop a program that identifies individual words in a sentence, stores these in a list and replaces each word in the original sentence with the position of that word in the list. For example, the sentence
MY NAME IS MY NAME IS MY NAME IS
The sentence can be recreated from the positions of these words in this list using the sequence 1,2,3,1,2,3,1,2,3
到目前为止,我得到的是:
sentence = input("Please enter a sentence that you would like to recreate")
x = sentence.split()
positions = [0]
for count, i in enumerate(a):
if x.count(i) < 2:
positions.append(max(positions) + 1)
else:
positions.append(x.index(i) +1)
positions.remove(0)
print(positions)
这重新创建了位置,但我需要做的是输出句子中的所有单词。在
例如,如果我写了一个句子Leicester city are champions of the premier league the premier league is the best
,我希望程序输出这个句子包含单词Leicester, city, are, champions, of, the, premier, league, is, best
。在
有人能帮我最后一点忙吗?在
使用您生成的位置,您可以通过列表理解或简单的for循环获取所需的列表部分。这里的关键是,当存储的数字以
1
开头时,python索引从0
开始。然后可以使用字符串的join
函数以逗号打印。在或者,使用for循环:
^{pr2}$相关问题 更多 >
编程相关推荐